Functions

James Wilkinson fedora at westexe.demon.co.uk
Tue Mar 14 13:15:22 UTC 2006


hbrhodes wrote:
> why is it that it only works in the format
> 
> function rar()
> {
> /path/to/rar/rar $@
> }
> 
> and not function rar() { /path/to/rar/rar $@ }

Short answer: newlines are "syntactically relevant" in shell script.
That is: a newline actually means something to the script, and taking
one out changes the meaning of the script.

Otherwise, if you typed in
echo Running rar...
/path/to/rar/rar
how would bash know that /path/to/rar/rar is a command to run, and not
something echo should output?

For this reason, you should be careful running scripts from e-mails and
magazines, in case there has been some inconvenient word-wrapping going
on.

In this case, bash expects there to be a newline before the last }, so
it can be sure that the } is supposed to be part of the shell script,
and not something that is passed to rar.

> also, if you don't mind, why is it that you used a $@ instead of a ;

They do *completely* different things...

; can act instead of a newline (unless it's quoted). So
echo Running rar... ; /path/to/rar/rar
is two separate commands.

$@ is a list of all the "words" you passed to the "rar" function. So if
you ran
rar one.rar two.rar three.rar
the shell variable $1 would be one.rar, $2 would be two.rar, $3 would be
three.rar, and $@ would be one.rar two.rar three.rar

If you don't include it, then the rar *shell function* gets
one.rar two.rar three.rar
and doesn't do anything with them (because it wasn't told to do anything
with them). The rar program is just run on its own.

This allows you to do things like
function archive()
{
    cp $@ archive/
}
and then do
archive important-project.tar.gz
and have "important-project.tar.gz" inserted into the *middle* of cp and
archive/.

Hope this helps,

James.
-- 
E-mail address: james | Helpful Advice from Thames Water:
@westexe.demon.co.uk  | "If you have difficulty reading this leaflet,
                      | please ask someone to help you."
                      |     -- Read on "The News Quiz", BBC Radio 4




More information about the fedora-list mailing list