Cacomania: Some bash special variables you should never forget


Some bash special variables you should never forget

Guido Krömer - 5. December 2012 - Tags: ,

Since the main topic here in the last time was JavaScript here is a small foray into the world of bash special variables. Although there are a lot more special variables in bash this might be the most common in my opinion.

Getting all params

There are two variables containing all params, the first one is $* which represents all params as single quoted string and $@ where each word is quoted separate. If it's not clear what is going on there, let's have a look at the example below.

echo STAR: ${ALL_ARGS_STAR[0]}
echo STAR: ${ALL_ARGS_STAR[1]}
echo AT: ${ALL_ARGS_AT[0]}
echo AT: ${ALL_ARGS_AT[1]}

Accesing the variables ALL_ARGS_STAR and ALL_ARGS_AT using the array indexer should make the difference of $* and $@ more clear.

[caco@MacBook-Air ~]# ./ Foo Bar 1337
STAR: Foo Bar 1337
AT: Foo
AT: Bar

The other usefull ones

  • $0, which is the first param and holds the called script name including the path.
  • $# represents the number of arguments.
  • $1 .. $n access the param directly.
  • $$ gets the PID of the running script.

If you got confused by $0, $#, $1337 or $$ have a look at the self explaining script below:

SCRIPT_NAME=`basename $0`

echo "Script name: $SCRIPT_NAME"
echo "Number of arguments: $NUM_ARGS"
echo "PID: $PID"
echo "Arg one: $ARG_ONE"
echo "Arg two: $ARG_TWO"

echo -e "Arg:\tVal:"
for ARG in $ALL_ARGS; do
  echo -e "$i\t$ARG"
  i=$(( $i + 1 ))

Here is the generated output:

[caco@MacBook-Air ~]# ./ Foo Bar 123
Script name:
Number of arguments: 3
PID: 25052
Arg one: Foo
Arg two: Bar
Arg:    Val:
1   Foo
2   Bar
3   123