Categories: Shell Script

Variables in the Linux Shell [Basic Guide]

Working with variables in the Linux Shell is essential for any system administrator, since they together with some commands give a lot of power and flexibility.

During the execution of bash, some special variables are maintained that contain some important information for the execution of the shell.

These variables are loaded at the start of the bash execution and can also be configured manually at any time.

PS1 and PS2 command prompt

The first variable that we are going to address is PS1 or simply Prompt String 1. This variable saves the content of the bash command prompt when it is ready to receive commands.

There is also the PS2 variable that stores the content of the command prompt when multiple lines are needed to complete a command.

These two shell variables do not affect how the interpreter will process incoming commands, but they can be of great help when loading extra information such as user name, current directory, etc.

This variable is roughly how the shell will present itself.

It was agreed that the variables are all written in an upper-case format.
But it’s important that you know that $name and $NAME are two different variables for the shell.

The content of any Shell variable can be viewed with
the echo command succeeded by the $ symbol plus the variable name:

$ echo $PS1

\ $

The character “\” says that any other character that succeeds it must be interpreted exactly as it is and not processed by the shell. He is what we call metacharacter.

It’s common for the standard bash command prompt to come in the form:

\ u@\ h:\ W\ $

The commands and variables in Linux are sensitive to uppercase and lowercase letters.

Each of these characters is interpreted in a special way. The “\u” is used to represent the user’s name, the “\h” is used to represent the system name (hostname) and the “\W” is the current directory. An example for this prompt is:

Look at @notebook:home$

PATH variable

Another important Shell variable is PATH. The path stores a list of the directories containing the programs that you can run without having to pass the full path to your location on the command line.

$ echo $PATH

/sbin:/bin:/usr/sbin:/usr/bin

It’s important that you know that the bash command interpreter

Follow the following order to find and execute the entered commands:

1) The command entered is an internal command from the command interpreter?

2) If not, the command it is an executable program located in some directory listed in the variable
PATH?

3) The location of the command explicitly stated?

An interesting tip is to include “:.” at the end of the PATH variable to have Bash include the current directory in its program search list executables. Unlike Windows and MS-DOS, the current directory is not included in standard search list, in most Linux distributions. 

Without including the “:.” in the PATH it is necessary to enter the relative path when calling programs in the current directory with ”./program_name”.

Listing variables in Linux

A complete list of shell variables can be obtained with the set command.

You can also change or create a new shell variable using the commands:

$ BOOK=” Linux Certification”

$ export BOOK

Preferably the variables must be declared in upper case and do not place spaces between the name of
variable, the symbol = and its content. If the content is alphanumeric it is desirable that it be enclosed in single or double quotes.

Difference between single quotes and double quotes in Linux

When the text of a Variable is a common sequence of letters and numbers, it doesn’t matter if you are going use single or double quotes.

$ PHRASE1=” This is a test”

$ PHRASE2=’Of the difference in quotation marks’ $ echo $PHRASE1

$ PHRASE2

This is a quotation mark difference test

But if you are going to use variables in quotes, there is a difference:

$ echo “$PHRASE1 $PHRASE2”

This is a quotation mark difference test

$ echo ‘$PHRASE1 $PHRASE2’

$ PHRASE1 $PHRASE2

So the double quotes expand the content of the variables, while not the single quotes.

This makes a difference if you want, for example, to include a directory in PATH variable:

$ echo $PATH
/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/opt/aws/bin:/home/ec2-user/bin

$ PATH=”$PATH: /oracle/admin/bin”

$ echo $PATH

/usr/local/bin:/bin:/bin:/usr/local/sbin:/usr/bin:/usr/local/sbin:/usr/bin:/usr/local/sbin:/usr/bin:/usr/local/sbin:/usr/bin:/usr/local/sbin:/usr/bin:/usr/local/sbin:/usr/bin:/usr/local/sbin:/usr/bin:/usr/local/sbin:/usr/bin:/usr/local/sbin:bin:/sbin:/opt/aws/bin:/home/ec2-user/bin:/oracle/admin/bin

 

In this case, single quotes wouldn’t work.

Export shell variables for use in programs

After creating a shell variable, you must export it to the environment with the export command.

When a variable is exported to the environment, it is available to all shell child processes (all programs and applications that you run in bash).

Each time a process is executed by the shell, it will only receive variables created by the shell if they are exported with the export command.

So the child process (the program that we want to execute) will inherit the variables created from the parent process (the shell).

See the example below, where we create a variable called BOOK:

$ BOOK=” Linux Certification”

echo $BOOK

Linux Certification

If we run bash again in the same terminal, to create a child process, you will see that the BOOK variable does not exist because it was not exported to the process’s son:

$ bash

$ echo $BOOK

Some words cannot be used as variables, since they are what we call reserved Bash words, used as internal commands.

Shell reserved words

They are: alias, alloc, bg, bind, bindkey, break, breaksw, builtins, case, cd, chdir, command, complete, continue, default, dirs, do, done, echo, echotc, elif, else, end, endif, endsw, esac, eval, exec, exit, export, false, fc, fg, filetest, fi, for, for each, getopts, glob, goto, hash, hashstat, history, hup, If, jobid, jobs, kill, limit, local, log, login, logout, ls-f, nice, nohup, notify, onintr, popd, printenv, pushd, pwd, read, readonly, rehash, repeat, return, sched, set, setenv, settc, setty, setvar, shift, source, stop, suspend, switch, telltc, test then,, time, times, trap, true, type, ulimit, umask, unalias, uncomplete, unhash, unlimit, unset, unsetenv, until, wait, where, which, while.

Set command

Use:

$ set [variable]

The set command informs a list of all local variables, environmental variables, and functions of
shell.

Some options of set commands change the behavior of bash, namely:

  • -C Prevent the output of a program using `>’, `>&’ and `<>’ from rewriting files. Even though the -o noclobber
  • -n option reads the commands but doesn’t execute them. Useful for checking scripts. Even though the option -o noexec
  • -P prohibits the shell from following symbolic links. Even though the option
  • -o physical -a Marks variables modified or created for export. Even though the option -o allexport
  • -o history enables saving the history of typed commands.

When using the options of set, the + symbol can be used to disable the options.

Unset command

Use:

$ unset [variable]

The unset command deletes an environmental variable from memory.

E.g.:

$ unset BOOK

Env command

Use:

$ env variavel=Program value

The env command is used to execute a program by sending a variable environmental. It enables a given program to read a variable without the need to export it with the export command. The -i option tells the env ignore the inherited environment without altering the content of any variable existing. It is useful for modifying a variable momentarily for a test.

E.g.:

$ env home=/home/guest2 programs

Pwd command

Use:

$ pwd

The pwd command reports the current absolute directory.

E.g.:

$ pwd

/usr/local

Uirá Endy Ribeiro

Uirá Endy Ribeiro is a Software Developer and Cloud Computing Architect with a 23-year career. He has master's degrees in computer science and fifteen IT certifications and is the author of 11 books recognized in the IT world market. He is also Director at Universidade Salgado de Oliveira and Director of the Linux Professional Institute - LPI Director's Board.

Uirá Endy Ribeiro

Uirá Endy Ribeiro is a Software Developer and Cloud Computing Architect with a 23-year career. He has master's degrees in computer science and fifteen IT certifications and is the author of 11 books recognized in the IT world market. He is also Director at Universidade Salgado de Oliveira and Director of the Linux Professional Institute - LPI Director's Board.

Recent Posts

Sudo command on Linux (privilege scale) [Basic Guide]

The sudo command on Linux executes a given command as if it were another user.…

2 years ago

SS command on Linux (investigate the network) [Basic Guide]

The ss command on Linux is extremely useful for investigating sockets, providing various information about…

2 years ago

Free Linux command (memory usage) [Basic Guide]

Free Linux command shows the amount of total memory in use and available, as well…

2 years ago

Linux while command (loop – while) [Basic Guide]

The shell has structures for testing conditions and executing certain program sequences several times (loop),…

2 years ago

Linux fstab file (disk mount setup) [Basic Guide]

The /etc/fstab file stores the configuration of which devices should be mounted and what is…

2 years ago

Netcat command on Linux (Swiss network knife) [Basic Guide]

The Netcat Command in Linux or nc is a utility used to do “almost anything”…

2 years ago

This website uses cookies.