Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 95 ยท Shell Scripting

Variables and Environment Variables

Learn Bash variables: assignment without spaces, $var vs ${var}, unset, readonly, export, the environment, special variables like $? $# $@, PATH and scope.

A variable is a named place to keep a piece of text. Scripts without variables would be long lists of fixed commands; with variables they can adapt: to a filename the user passes in, to the result of an earlier command, to a setting that changes between your laptop and a server.

Bash variables are simpler than in most languages, and also stranger. Everything is a string unless you ask otherwise; there are no spaces allowed around =; and the shell, not the language, decides how a value is split when you use it. This lesson covers the rules, the difference between shell variables and environment variables, the special variables the shell sets for you, and the habits that prevent the classic mistakes.

Assigning and reading

You assign with name=value and read with $name. There must be no spaces around the equals sign:

Bash Assigning and using variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Why the error? With spaces, Bash reads greeting as a command name and = and "hi" as its arguments. It reports greeting: command not found (status 127). In name=value form the shell sees an assignment, because the word contains = right after a valid name.

Names may contain letters, digits and underscores, and cannot start with a digit. They are case sensitive, so Name, name and NAME are three variables. By convention, UPPER_CASE is used for environment variables and constants, lower_case for variables local to a script. Using lower case for your own variables avoids accidentally overwriting something the system uses, such as PATH or HOME.

$var versus ${var}

$name is short for ${name}. You need the braces when the characters following the name could be mistaken for part of it, and for the advanced features you will meet in Parameter Expansion and String Handling.

Bash Why braces matter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Always quote the expansion

When you write $var without quotes, the shell splits the value on whitespace and then expands wildcards in the pieces. Quoting, "$var", keeps it as one word. This is so important that Quoting and Expansion is a lesson of its own; for now just remember the habit: quote every $ unless you know why not.

Bash Unquoted variables split and glob

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Removing and protecting variables

  • unset name deletes a variable. Reading an unset variable gives an empty string, which is quietly a source of bugs.
  • readonly name=value (or declare -r) makes it constant; assigning again is an error.
  • set -u makes reading an unset variable an error, which catches typos. Exit Codes, set -e and Error Handling discusses it.
Bash unset, readonly and set -u

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Variables, the environment and export

Bash has two kinds of variables:

  • A shell variable lives inside the shell process.
  • An environment variable is a shell variable that has been exported. Every program the shell starts receives a copy of the exported ones, as its environment.
TEXT
   shell process
   +-----------------------------------------+
   |  local=1            (shell variable)    |
   |  EDITOR=vim  *      (exported)          |      starts a program
   |  PATH=...    *      (exported)  ------- | ---> that program sees only
   +-----------------------------------------+      EDITOR and PATH

export name marks an existing variable, and export name=value assigns and marks in one step. The flow is one-way: a program can change its own copy but never the parent's. Subshells, Groups and Environment explains the mechanics.

Bash Seeing the environment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The NAME=value command form is the clean way to give one program a setting without changing your shell. declare -p prints how Bash holds a variable: the x attribute means exported.

Special variables

The shell maintains a set of variables for you. They are read-only; you cannot assign to them.

Variable Meaning
$? Exit status of the last command
$$ Process ID of the shell
$! Process ID of the last background job
$0 Name of the script (or shell)
$1, $2, โ€ฆ ${10} Positional parameters: the arguments
$# Number of arguments
"$@" All arguments, each as a separate word
"$*" All arguments joined into one word with the first character of IFS
$_ Last argument of the previous command
$- Current shell option flags

The two that matter most for scripts are "$@" and $#. Because the editor runs your example as a script without arguments, use a function to demonstrate them (functions have their own positional parameters, see Functions):

Bash Positional parameters, $@ and $*

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

set -- "a b" "c" sets the positional parameters of the current shell. The difference between "$@" (2 args) and unquoted $@ (3 args) is the whole reason these notes insist on quotes. The rule: always write "$@".

Bash Status, PID and script name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

If you need a status later, save it at once: status=$?.

Important built-in variables

Some variables are set by the system or the shell and affect what programs do:

Variable Used for
HOME Your home directory (what ~ expands to)
PATH Directories searched for commands, separated by :
PWD, OLDPWD Current and previous directory
USER / LOGNAME Login name (may be unset in containers)
SHELL The user's login shell
LANG, LC_ALL, TZ Locale and time zone
IFS Characters used for word splitting
RANDOM, SECONDS, LINENO Magic values maintained by Bash

PATH in detail

When you type a command with no slash, Bash looks through the directories in PATH from left to right and runs the first match. Adding a directory at the front gives it priority, at the end makes it the fallback.

Bash How PATH finds commands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Never put . (the current directory) or an empty entry in PATH: a malicious file named ls in a download folder could then run in your place.

RANDOM, SECONDS and LINENO

RANDOM returns a number between 0 and 32767. Assign a number to it to seed the sequence, which makes results reproducible. SECONDS counts the seconds since the shell started. LINENO is the current line number of the script.

Bash Magic variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Scope: global, local and loops

A variable assigned in a script is global to the whole script, including functions. Inside a function, local name=value creates a variable that exists only there and in the functions it calls. Without local, a function silently overwrites a variable of the caller:

Bash Global versus local

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Rule: declare every function variable with local. Typos aside, this is the main way to keep functions independent.

Types: integers, arrays and constants

Bash stores text, but declare can give a variable attributes:

  • declare -i n forces integer arithmetic on assignment: n=2+3 stores 5.
  • declare -r read-only, declare -x exported (same as export), declare -l / -u convert to lower or upper case.
  • Arrays (declare -a, declare -A) are the topic of Arrays and Associative Arrays.
Bash declare attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

More declare: scope, functions and listing

Three more uses of declare come up in scripts:

  • declare -g name=value creates or changes a global variable even when called inside a function (inside a function, a plain declare makes a local one).
  • declare -p name prints a variable with its attributes, in a form you can paste back; declare -p alone lists every variable.
  • declare -f name prints a function's source and declare -F lists the function names only. These two are how you answer "which functions are defined?".
Bash declare -g, -f, -p and -F

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Naming and style checklist

  • Quote every expansion: "$name".
  • Use lower_case for script variables and UPPER_CASE for exports and constants.
  • Give names meaning: backup_dir, not d.
  • Use readonly for constants and local in functions.
  • Do not export unless a child program needs the variable.
  • Keep secrets out of exported variables when you can: every program you start, and anything that can read its environment, receives them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line correctly assigns the text hello world to a variable?

    There must be no spaces around =, and a value with a space needs quotes. Line 1 runs a command called greeting, line 2 runs 'world' with greeting set to hello, and you never put $ in front of the name when assigning.
  2. 2. What is the difference between a shell variable and an environment variable?

    export marks a variable so it is passed to child programs. Plain shell variables stay in the shell.
  3. 3. A script is called as ./s.sh "a b" c. How many words does "$@" produce?

    "$@" keeps each original argument as a separate word: 'a b' and 'c'. Unquoted $@ would produce 3 words.
  4. 4. What does $? hold?

    $? is the exit status of the last command; $# counts arguments and $$ is the shell's PID.
  5. 5. Inside a function you write i=0 without local, and the caller uses a variable called i. What happens?

    Variables are global by default. Use local i inside the function to keep it private.

Summary

  • Assign with name=value (no spaces); read with $name or ${name}; quote expansions as "$name".
  • Unset variables expand to nothing; set -u turns that into an error. readonly makes a constant.
  • export turns a shell variable into an environment variable that child programs inherit; VAR=x command sets it for one command.
  • Special variables: $? status, $$ PID, $! last background PID, $0 name, $1โ€ฆ arguments, $# count, "$@" all arguments.
  • PATH is searched left to right for commands; never include . in it.
  • Variables are global by default; declare function variables with local.
  • declare gives variables attributes such as integer, read-only or upper-case.

Next: Quoting and Expansion