Cacomania: Some bash special variables you should never forget

Cacomania

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.

#!/bin/bash
ALL_ARGS_STAR=("$*")
echo STAR: ${ALL_ARGS_STAR[0]}
echo STAR: ${ALL_ARGS_STAR[1]}
ALL_ARGS_AT=("$@")
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 ~]# ./params-list.sh Foo Bar 1337
STAR: Foo Bar 1337
STAR:
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:

#!/bin/bash
SCRIPT_NAME=`basename $0`
NUM_ARGS=$#
PID=$$
ARG_ONE=$1
ARG_TWO=$2
ALL_ARGS=$@

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

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

Here is the generated output:

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