while reading about linux file searching I got the following...
To search for files using the * wildcard, replace the unknown string with *, e.g. if you remember only that the extension was .out, type ls *.out
and when I tried the following command on system(ubuntu 14.04 LTS) ..I got
anupam@JAZZ:~$ ls *.bash*
ls: cannot access *.bash* : No such file or directory
anupam@JAZZ:~$ ls .bash*
.bash_history .bash_logout .bash_profile .bashrc
anupam@JAZZ:~$
in the first case why it is showing No such directory ( *.bash*
) and in next case its showing the files ( .bash*
)
I am new to this flavor, and according to my automata theory classes (*) means any combination of strings including epsilon(empty),,So why the results are different in both the cases....?
When you do
ls *
the*
is being expanded before it is passed tols
. That is to say if we have three files (a
,b
andc
) in a directoryls *
is actually runningls a b c
.When Bash can't expand, it passes through the raw string¹. That's why you see the wildcards in the error, along with a not found message.
ls
tried to show the listing for a file literally called*.bash*
.So why didn't that expand? Well by default globbing (what this wildcard expansion is called) won't return hidden files. You can change this with
shopt -s dotglob
(that won't persist unless you stick it in your.bashrc
— it might be disabled by default for a good reason so be careful with it), here's a quick demo:The exception to this is —as you've already shown— when you've already explicitly stated the files will be hidden with a pattern like
.bash*
. It simply overrides the defaultdotglob
setting:Anyway besides that quirk, I hope this helps you understand what's going on under the surface.
There are other
shopt
flags that alter how globbing works:extglob
,failglob
,globstar
,nocaseglob
andnullglob
. They and a raft of othershopt
flags are documented as part of the Bash manual.Similarly, the page on Pattern Matching should make for some good reading.
¹ Unless
failglob
ornullglob
are set.