BASH Variables

From CDOT Wiki
Jump to: navigation, search

BASH supports one type of variable: a string. Variables may be interpreted as integers or booleans (True/False) when appropriate.

Creating or Assigning a Variable

To create a variable or change the value assigned a value to a variable, write the variable name, an equal sign, and the value, with no space:

X=5
COLOUR="Red"
NAME="Jason Smith"
EMAIL="jsmith@example.com"

Variable names must start with a letter and contain only letters, underscores, and digits. Variable names are case-sensitive, and UPPERCASE is often used to make it easy to distinguish between variable names and commands and arguments.

Reading a Variable

The read command will read a line of input from stdin and assign it to a variable:

read INPUT

This example will read a line of input from stdin (usually the keyboard) and assign it to the variable INPUT.

Seeing All Variables

The set command will display the value of all current variables:

$ set
BASH=/bin/bash
BASH_ARGC=()
BASH_ARGV=()
BASH_LINENO=()
BASH_SOURCE=()
BASH_VERSINFO=([0]="3" [1]="2" [2]="33" [3]="1" [4]="release" [5]="x86_64-redhat-linux-gnu")
BASH_VERSION='3.2.33(1)-release'
COLORS=/home/chris/.dir_colors.xterm
COLORTERM=gnome-terminal
COLUMNS=80
CVS_RSH=ssh
DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-fFVokEovDE,guid=4eb682a22a695ccd33b24f0048cad335
DESKTOP_SESSION=default
DESKTOP_STARTUP_ID=
DIRSTACK=()
DISPLAY=:0.0
EUID=500
GDMSESSION=default
GDM_LANG=en_US.UTF-8
GDM_XSERVER_LOCATION=local
GNOME_DESKTOP_SESSION_ID=Default
GNOME_KEYRING_PID=3441
GNOME_KEYRING_SOCKET=/tmp/keyring-jBoBFl/socket
GROUPS=()
GTK_MODULES=gnomebreakpad
GTK_RC_FILES=/etc/gtk/gtkrc:/home/chris/.gtkrc-1.2-gnome2
G_BROKEN_FILENAMES=1
HISTFILE=/home/chris/.bash_history
HISTFILESIZE=1000
HISTSIZE=1000
HOME=/home/chris
HOSTNAME=concord3.proximity.on.ca
HOSTTYPE=x86_64
IFS=$' \t\n'
INPUTRC=/etc/inputrc
KDEDIRS=/usr
KDE_IS_PRELINKED=1
LANG=en_US.UTF-8
LESSOPEN='|/usr/bin/lesspipe.sh %s'
LINES=24
LOGNAME=chris
LS_COLORS='no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05; 
37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00; 
31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00; 
31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00; 
35:*.xpm=00;35:*.png=00;35:*.tif=00;35:*.doc=01;37;45:'
MACHTYPE=x86_64-redhat-linux-gnu
MAIL=/var/spool/mail/chris
MAILCHECK=60
OPTERR=1
OPTIND=1
OSTYPE=linux-gnu
PATH=/usr/kerberos/bin:/usr/lib64/ccache:/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/home/chris/bin
PIPESTATUS=([0]="0" [1]="0")
PPID=21127
PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}"; echo -ne "\007"'
PS1='[\u@\h \W]\$ '
PS2='> '
PS4='+ '
PWD=/home/chris
SDL_AUDIODRIVER=esd
SESSION_MANAGER=local/unix:@/tmp/.ICE-unix/3442,unix/unix:/tmp/.ICE-unix/3442
SHELL=/bin/bash
SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
SHLVL=2
SSH_AGENT_PID=3503
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
SSH_AUTH_SOCK=/tmp/ssh-JdPTTt3442/agent.3442
TERM=xterm
UID=500
USER=chris
VIRSH_DEFAULT_CONNECT_URI=qemu:///system
WINDOWID=102760527
WINDOWPATH=7
XAUTHORITY=/tmp/.gdmYDNCHU
XDG_DATA_DIRS=/usr/local/share/:/usr/share/:/usr/share/gdm/
XDG_SESSION_COOKIE=8d5bac776a73b1f9ff24d500473f1f00-1221251892.355110-634173433
_=
colors=/home/chris/.dir_colors.xterm
consoletype=pty

Using a Variable's Value

To use the value of a variable in a command, place a dollar sign in front of the variable name:

echo "$COLOUR"
mail -s "Today's colour is $COLOUR" "$NAME <$EMAIL>" </tmp/message
if [ "$X" -eq 5 ]
then
   echo "Hooray!"
fi

Variables are interpolated when in double-quotes, but not when they are in single-quotes:

$ X="Test"
$ echo "$X"
Test
$ echo '$X'
$X
$ echo $X
Test

One advantage to using double-quotes is that the variable value will be treated as a single argument even when it contain spaces. For example:

$ touch "test file"
$ NAME="test file"
$ rm $NAME
rm: cannot remove `test': No such file or directory
rm: cannot remove `file': No such file or directory
$ rm "$NAME"

You may optionally place the variable name within curly-braces (useful if there is text immediately after the variable name):

NUMBER="12"
echo "You are in ${NUMBER}th place!"

Adding to a Variable

To add to a variable, assign a value to it which contains the existing value plus new data. For example, to add ":." to the end of the PATH variable:

PATH="$PATH:."

Exporting Variables

Shell variables may be turned into environment variables, which causes them to be inherited by subprocesses:

$ TEST="Yes"
$ bash -c 'echo $TEST'
  
$ export TEST
$ bash -c 'echo $TEST'
Yes
$

Destroying Variables

A variable will be destroyed when the shell in which it was created exits. You can destroy it using the unset command:

$ Z=100
$ echo $Z
100
$ unset Z
$ echo $Z
 
$

Special Variables

BASH automatically updates the value of certain special variables:

Variable Description
$? Exit status of last pipeline
$$ Process ID of the current shell
$! Process ID of the last background pipeline
$RANDOM Random integer (usually in the range 0-327687).

Common Environment Variables

Linux systems use a number of common environment variables:

Variable Description
$PATH List of colon-separated directories to be used when searching for a command.
$HOME Current user's home directory.
$MAIL Current user's mailbox.
$DISPLAY X window display specification.
$TERM Current terminal type (used to analyze keypresses and send special codes such as colours and effects to the terminal).
$SHELL Absolute pathname of the default shell for the current user.
$HOSTNAME Name of the host (computer) on which the shell is executing.
$PS1 Primary prompt, used by the shell to request a command from the user.
$PS2 Secondary prompt, used to request additional info from the user.
$PS3 3rd prompt (rarely used).
$PS4 4th prompt (rarely used).