The first set of variables we will look at are $0 .. $9 and $#.
The variable $0 is the name of the program as it was called.
$1 .. $9 are the first 9 additional parameters the script was called with.
The variable $@ is all parameters $1 .. whatever. As a general rule, use $@ and avoid $*.
$# is the number of parameters the script was called with.
Let's take an example script:
#!/bin/shecho"I was called with $# parameters"echo"My name is $0"echo"My first parameter is $1"echo"My second parameter is $2"echo"All parameters are $@"
Note that the value of $0 changes depending on how the script was called.$# and $1 .. $9 are set automatically by the shell.We can take more than 9 parameters by using the shift command
This script keeps on using shift until $# is down to zero, at which point the list is empty.
Another special variable is $?. This contains the exit value of the last run command. So the code:
will attempt to run /usr/local/bin/my-command which should exit with a value of zero if all went well, or a nonzero value on failure. We can then handle this by checking the value of $? after calling the command. This helps make scripts robust and more intelligent.Well-behaved applications should return zero on success.
The other two main variables set for you by the environment are $$ and $!. These are both process numbers.
The $$ variable is the PID (Process IDentifier) of the currently running shell. This can be useful for creating temporary files, such as /tmp/my-script.$$ which is useful if many instances of the script could be run at the same time, and they all need their own temporary files.
The $! variable is the PID of the last run background process. This is useful to keep track of the process as it gets on with its job.
curly brackets around a variable avoid confusion:
The following code snippet which prompts the user for input, but accepts defaults:
Passing the "-en" to echo tells it not to add a line break.
This script runs like this if you accept the default by pressing "RETURN":
This could be done better using a shell variable feature. By using curly braces and the special ":-" usage, you can specify a default value to use if the variable is unset:
There is another syntax, ":=", which sets the variable to the default if it is undefined:
This technique means that any subsequent access to the $myname variable will always get a value, either entered by the user, or "John Doe" otherwise.