Just like most other programming or scripting languages, Bash supports variables. A variable is simply a name given to a piece of data. We can use the name to refer to the data. The value of a variable name can be changed, which is why it’s called variable.

Try it out in your terminal:

name="Bob"
echo $name
name="Alice"
echo $name

Notice that the second echo outputs something else even tho the line is exactly the same. We use $name (with $) to refer to the variable. Otherwise we would just get the text “name”.

If you want to assign a variable to something that the user can enter while your script is running, then you can use the read command.

read $name
echo "Hello $name"

If we have variables with numbers, we can do simple arithmetic with them.

a=3
b=7
echo $((a + b))

Variables are not accessible to sub-commands by default. We can test this by typing:

foo="foo"
bash -c 'echo $foo'

Notice you get blank line from echo command.

If we want to make variables available to sub-commands we can do this by exporting it.

export foo="foo"
bash -c 'echo $foo'

Now echo in sub-shell can access the $foo variable from it’s parent environment.

Exported variables are also called environment variables (aka envvar). Your shell likely have a bunch of envvars set already. You can view them with either “export -p” or “env” command.

Let’s examine a couple.

# The shell you are using
echo $SHELL
# Your terminal
echo $TERM
# The default text editor
echo $EDITOR
# Whether your graphical environment is wayland or x11
echo $XDG_SESSION_TYPE
# Your home (user) folder
echo $HOME
# Where your shell with search for commands
echo $PATH

The $PATH envvar deserves a bit more attention. This is a list of paths your shell will search for commands. If you type “python” it will search for a file named “python” in any of the listed folders then execute it. If it can’t find the command it will print “command not found”.

Having a PATH variable avoids having you type out the full path of each command.

When you install CLI tools to your home folder, it might tell you to modify the PATH variable by adding a line to the configuration file for your shell, such as .bashrc for Bash or .zshrc for Z-shell. Example:

export PATH=$PATH:$HOME/.dotnet/tools

It tells bash to look commands in folders previously defined in $PATH and .dotnet/tools from within your home folder.