Unix 101 : Shell wildcards expansion, to quote or not to quote

Or why you usually use ls -l *txt without quotes, but use quotes in find . -name "*txt".

 

Wildcards expansion is a feature of the shell which identifies files by a pattern instead of a comprehensive list. For example if you have a directory with the following 10 files all starting by the letter “a” and 10 files all starting by the letter “b” :

kattoo@roadrunner test % ls                                        
a01  a03  a05  a07  a09  b01  b03  b05  b07  b09
a02  a04  a06  a08  a10  b02  b04  b06  b08  b10
kattoo@roadrunner test %

and you want the detailed listing of only all of those starting with “a”.

 

You can do either :

kattoo@roadrunner test % ls -l a01 a02 a03 a04 a05 a06 a07 a08 a09 a10
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a01
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a02
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a03
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a04
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a05
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a06
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a07
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a08
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a09
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a10

or the much shorter :

kattoo@roadrunner test % ls -l a*                                     
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a01
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a02
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a03
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a04
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a05
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a06
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a07
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a08
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a09
-rw-r--r-- 1 kattoo kattoo 0 Jan 24 08:42 a10
kattoo@roadrunner test %

In the second form you ask the shell to identify all the files starting with an “a” followed by any character, and to provide them as arguments to the command ls. Both forms are equivalent.

 

Now, some tools are capable of interpreting patterns on their own. find or grep are such tools. In that situation, you do not want the shell to interpret the patterns and replace them by the matching files before providing them as command line arguments.

 

You do that by quoting the patterns, thus explicitly instructing the shell to leave the patterns alone and to provide the pattern (and not the matching files) directly as command line arguments to the command.

 

Example :

kattoo@roadrunner Downloads % find . -name "*.tar.gz" | egrep "open.*2"
./pyopencl-2011.2.tar.gz
kattoo@roadrunner Downloads %

Here the patterns are quoted so that the shell won’t try to replace them by matching files. find and grep will get the patterns as command line arguments directly and process them to respectively find the matching files and filter the matching lines.

 

Leave a Reply

Your email address will not be published. Required fields are marked *