Variables

Bash · Essentials · 8 min

Variables hold paths, names and settings in every script and are the first thing you expand.

Assign with name=value and no spaces around `=`: name = value would run a command called name. Read a variable with $name, or ${name} when the name must be separated from following text, as in ${name}_backup.

Every bash variable is a string unless you declare otherwise; count=5 stores the text 5, and arithmetic happens only inside $(( )). Referencing a variable that was never set silently gives an empty string, which is why typos are dangerous (strict mode, later, fixes that). Remove a variable with unset name and protect one with readonly NAME=value; assigning to a read-only variable is an error that aborts a non-interactive script.

Bash maintains several special parameters:

  • $? exit status of the last command, $$ PID of the shell,
  • $0 script name, $1, $2... positional arguments, $# how many,
  • $RANDOM a random integer, $PWD the current directory, $HOME your home.

Convention: lower-case names for your own script variables and UPPER_CASE for environment variables and constants, so you never clobber PATH or HOME by accident. Values with spaces must be quoted when assigned: title="My report".

Example

name="Ada"                  # no spaces around =
greeting="Hello, $name"
echo "$greeting"            # Hello, Ada
echo "${name}_backup"       # Ada_backup  (braces delimit the name)
count=5
echo "$count + 1"           # 5 + 1       (just text)
echo "$(( count + 1 ))"     # 6           (arithmetic expansion)
unset name
echo "[$name]"              # []          (unset expands to empty)
readonly PI=3.14
declare -p PI               # declare -r PI="3.14"
echo "PID $$, last status $?"

Remember

  • name=value with no spaces; read it with "$name" or "${name}"
  • Unset variables expand to an empty string, silently
  • Use lower-case names for script variables, UPPER_CASE for environment ones

Watch out for

  • Writing x = 5: bash runs a command named x with arguments = and 5.

Check yourself

  1. What does `greeting = hi` do in bash?
  2. After `v=10`, what does `echo "$v1"` print?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.gnu.org/software/bash/manual/bash.html#Shell-Parameters