[juneau-lug] Re: What does . mean?

  • From: "James Zuelow" <jamesz@xxxxxxxxxxxxxxxx>
  • To: <juneau-lug@xxxxxxxxxxxxx>
  • Date: Thu, 27 Mar 2003 14:55:38 -0800

OK, here's a quick example of what we're talking about.  This is going
to be boring for people who script a lot, but I know that some of you
are just learning how to script so it might be useful to try this out
and experiment a little.

Basically, you can give arguments to a script like this:

Script.sh arg1 arg2

This is just like giving arguments to a command (for example, `ls -h`
modifies the ls command.)

Within your script, you can retrieve the arguments given by using
"positional parameters" like so:

echo "Argument One: "$1" Two: "$2

(this would return "Argument One: arg1 Two: arg2")

When a script starts, it is created in it's own environment.
Essentially, it comes alive in it's own little universe, and it does not
necessarily know the same things that the script (or human) that called
it know.  When the script finishes, it's environment dies along with it,
including anything it may have learned along the way that hasn't been
saved somehow.

To play with this, write three small scripts as shown, place them in
your home directory, and make them all executable.  I'm playing with
this on OpenBSD using the sh shell, but it should work in Linux bash as
well:

testone.sh:

#This script will forget
#the positional arguments
#when it runs the second script.
~/testthree.sh

testtwo.sh:

# This test will retain the arguments
# from this script when it runs the
# second script.
. ~/testthree.sh

testthree.sh:

echo "Hello, "$1"."

Now run the first two scripts.  `~/testone.sh Kevin` should give the
following output:

Hello, .

This is because when testthree.sh was called from testone.sh, it was
created in it's own environment.  It was not passed any arguments, so $1
is null.

On the other hand, `~/testtwo.sh Kevin` should give the following
output:

Hello, Kevin.

In this case, because testthree.sh was called with the ., it used the
same environment that testtwo.sh was operating in.  And testtwo.sh had a
value for $1 - Kevin (or whatever you typed in).  Because the two
scripts are in the same environment, they see the same value for $1.

And of course running `~/testthree.sh Kevin` would give the same result.
In this case, testthree.sh has it's own environment, but it was passed
an argument so has a value for $1.

Anyway, pretty useful for passing arguments to sub-scripts.  There's
been a few times that I could have used this to simplify a script, and
just didn't know that using . was my solution.

Cheers,

James


------------------------------------
This is the Juneau-LUG mailing list.
To unsubscribe, send an e-mail to juneau-lug-request@xxxxxxxxxxxxx with the 
word unsubscribe in the subject header.

Other related posts: