Docs  >   Bash Handbook   >   Variables

Top

Variables

Like in most programming languages, you can also create variables in bash.

Bash knows no data types. Variables can contain only numbers or a string of one or more characters. There are three kinds of variables you can create: local variables, environment variables and variables as positional parameters.

Local variables

Local variables are variables that exist only within a single script. They are inaccessible to other programs and scripts.

A local variable can be declared using = sign (as a rule, there should not be any spaces between a variable's name, = and its value) and its value can be retrieved using the $ sign. For example:

username="denysdovhan"  # declare variable
echo $username          # display value
unset username          # delete variable

We can also declare a variable local to a single function using the local keyword. Doing so causes the variable to disappear when the function exits.

local local_var="I'm a local value"

Environment variables

Environment variables are variables accessible to any program or script running in current shell session. They are created just like local variables, but using the keyword export instead.

export GLOBAL_VAR="I'm a global variable"

There are a lot of global variables in bash. You will meet these variables fairly often, so here is a quick lookup table with the most practical ones:

Variable Description
$HOME The current user's home directory.
$PATH A colon-separated list of directories in which the shell looks for commands.
$PWD The current working directory.
$RANDOM Random integer between 0 and 32767.
$UID The numeric, real user ID of the current user.
$PS1 The primary prompt string.
$PS2 The secondary prompt string.

Follow this link to see an extended list of environment variables in Bash.

Positional parameters

Positional parameters are variables allocated when a function is evaluated and are given positionally. The following table lists positional parameter variables and other special variables and their meanings when you are inside a function.

Parameter Description
$0 Script's name.
$1 … $9 The parameter list elements from 1 to 9.
${10} … ${N} The parameter list elements from 10 to N.
$* or $@ All positional parameters except $0.
$# The number of parameters, not counting $0.
$FUNCNAME The function name (has a value only inside a function).

In the example below, the positional parameters will be $0='./script.sh', $1='foo' and $2='bar':

./script.sh foo bar

Variables may also have default values. We can define as such using the following syntax:

 # if variables are empty, assign them default values
: ${VAR:='default'}
: ${1:='first'}
# or
FOO=${FOO:-'default'}