[lug] help! shell script

Dave Brown dbrown at scd.ucar.edu
Tue Jan 11 10:47:22 MST 2000


> 
> > hi friends,
> > 
> > 
> > I was writing a shell script to uncompress all the files in the
> > directory.
> > 
> > The shell script available below just uncompressed one file.
> > 
> > The funny thing was that when i did a gzip using this shell
> > script it compressed
> > 
> > all the files....Can any one help
> > 
> > ------------------------------------------------------------
> > #!/bin/bash
> > for a in '*.tar.gz'
> > do
> >         tar zvxf $a
> > done
> > -------------------------------------------------------------
> 
> You want to use back-quotes, not forward quotes, on your for loop:
> Like this:
> 
> for a in `*.tar.gz`
>  .
> .
>  .
> 
Well, regardless of what the '`' character is called, the suggestion
above does not work. The back quote syntax causes the shell to execute
whatever is inside it, returning its output as the result. Since tar.gz
files are not executable (at least conventionally) you will (should)
get an error, such as:

[home] for a in `*.tar.gz`
> do
> echo $a
> done
bash: ./9905084.tar.gz: Permission denied
 
You could do:

[home] for a in `ls *.tar.gz`
> do
> echo $a
> done
9905084.tar.gz
doc.tar.gz
f2c.tar.gz

By the way, note that the echo command is useful for testing how a for
loop expands its argument. If you try your original script with echo you
get:

[home] for a in '*.tar.gz'
> do
> echo $a
> done
9905084.tar.gz doc.tar.gz f2c.tar.gz

whereas if you try removing the quotes you get:

[home] for a in *.tar.gz
> do
> echo $a
> done
9905084.tar.gz
doc.tar.gz
f2c.tar.gz

The difference is that in the original case the command 'echo' only gets
invoked one time with (effectively) three arguments, whereas in the 
second case it is invoked multiple times, with one argument each time. This 
behavior follows from the quoting rules for the bash shell.  

 -Dave Brown
 dbrown at ucar.edu










More information about the LUG mailing list