Advanced Shell Topics: Shell variables and arrays


Shell variables are just like variables in any other programming language such as C, Perl, Java or PHP. In BASH, they are most simular to variables in Perl or in PHP because of the way they look and how you reference them.

The dollar sign variables

The dollar sign is put before the name of a variable to denote that you're referencing the value that the variable holds. We can use the echo command to show this:

  [user@host ~]$ variable="Cheesy Poofs"
  [user@host ~]$ echo $variable
  Cheesy Poofs
  [user@host ~]$

The shell also automatically sets some special variables for you while you're using the shell. Whenever you execute a command such as a shell script, the shell sets positional variables for the arguments that are passed to the script. So if we have a script that looks like this:

#!/usr/bash
echo "zeroth argument: $0"
echo "first argument:  $1"
exit

  [user@host ~]$ ./script.sh hello
  zeroth argument: ./script.sh
  first argument: hello
  [user@host ~]$ 

You'll see that when executing the script with one argument, $1 is set to the first argument and $n is the nth argument. $0 is always the name of the invoking process. In this case that invoking process is called ./script.sh, but notice what happens when we echo $0:

  [user@host ~]$ echo $0
  bash
  [user@host ~]$ 

In the case above, the shell you are running was what invoked the echo command so $0 is bash, not echo. Below is a list of other common and useful variables automatically set by the shell

Variable Description
PPID Parent process ID.
SHLVL Depth of shell. For every instance of bash that is started from the top, this variable is incremented by one.
PWD Current working directory.
OLDPWD Previous working directory. Try 'cd -' sometime.
RANDOM Random number between 0 and 32767 for every invocation.
SECONDS Number of seconds since shell was invoked.
UID UID of user invoking the process.
EUID Effective UID of process.
GROUPS Array containing all the groups the user is in.
TMOUT Number of seconds bash will wait for input before terminating.
HISTSIZE Number of commands to remember in your shell history
PS1 Variable that allows you to customize what your prompt looks like.

Also please note that case is important and that setting $variable would have a different effect than setting $VARIABLE. If you are going to be setting your own variables though it's recommended that you use lower case variable names or letters for your own variables in a shell script or command line, and leave the upper case variables for shell built-ins and your normal environment variables


Arrays

There are also arrays in bash, both predefined and definable. You set them using a subscript notation and get at the values like this:

  [user@host ~]$ array[0]="value1"
  [user@host ~]$ array[1]="value2"
  [user@host ~]$ echo ${array[0]}
  value1
  [user@host ~]$ echo ${array[1]}
  value2

© 2000 Suso Banderas - suso@suso.org