coreutils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How the ls command interpret this?


From: Eric Blake
Subject: Re: How the ls command interpret this?
Date: Mon, 3 Jul 2017 12:17:28 -0500
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Thunderbird/52.2.0

On 07/03/2017 11:16 AM, BaBa wrote:
> Hello,
> 
> touch a[b]
> ls ?[b]

Well, the correct answer is: it depends on what is in your current
directory before you start things.  Here's some examples, all of which
produce different ls output, even though all of them include your two
commands verbatim in the middle:

Case 1:
$ mkdir foo
$ cd foo
$ touch ab
$ touch a[b]    # which re-touches 'ab' thanks to globbing
$ ls ?[b]       # which matches 'ab' thanks to globbing
ab
$ cd ..
$ rm -rf foo

Case 2:
$ mkdir foo
$ cd foo
$ touch bb
$ touch cb
$ touch a[b]    # the glob doesn't match, so it is passed unchanged
$ ls ?[b]       # the glob matches two out of three files
bb  cb
$ cd ..
$ rm -rf foo

Case 3:
$ mkdir foo
$ cd foo
$ touch a[b]    # the glob doesn't match, so it is passed unchanged
$ ls ?[b]       # the glob doesn't match, so it is passed unchanged
ls: cannot access '?[b]': No such file or directory
$ cd ..
$ rm -rf foo

Case 4:
$ mkdir foo
$ cd foo
$ touch '?[b]'  # no globbing involved, touches the file ?[b]
$ touch a[b]    # the glob doesn't match, so it is passed unchanged
$ ls ?[b]       # the glob doesn't match, so it is passed unchanged
'?[b]'
$ cd ..
$ rm -rf foo

In case 4, note that I'm using a new-enough version of ls that
automatically quotes its output so that it is suitable for reinput to
the shell (the '' are added to show that I want quoting in place, to
avoid the shell interpreting my filename as a glob).

There's also possibilities if you have a shell that supports options on
how globbing behaves (here, I'm using bash):

Case 5:
$ mkdir foo
$ cd foo
$ shopt -s failglob
$ touch a[b]
bash: no match: a[b]
$ shopt -u failglob
$ shopt -s nullglob
$ touch a[b]
touch: missing file operand
Try 'touch --help' for more information.
$ cd ..
$ rm -rf foo

But by now, hopefully I've answered your question.  If not, write 'echo'
instead of 'ls' on every command line that you are unsure of how the
shell will glob things, and thus on what arguments are being handed to ls.

-- 
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]