fbpx Linux Shell Variables: export, $VAR, and .bashrc | Certificação Linux

Linux Shell Variables: Create, Export, and Use in Scripts

📅 04/01/2019 ⏱ 8 min ✍️ Uira Ribeiro
Linuxhow-to
Linux Shell Variables: Create, Export, and Use in Scripts
Exam Pass App — mais de 7.000 questões LPI, offline, em 5 idiomas, disponível no Android e na App Store
Available on
Google Play
Available on
App Store

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

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

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

&list=PL6IznNGWCdD89jP8kiacplFQcJlmMmjhb&index=121

PS1 and PS2 Command Prompt

The first variable we will cover is PS1 or simply Prompt String 1. This variable holds the content of the bash command prompt when it is ready to receive commands.

There is also the PS2 variable which holds 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 the received commands, but they can be very helpful when they carry extra information such as username, current directory, etc.

This variable is roughly how the shell will introduce itself.

It is conventional that variables are all written in uppercase. But it is important that you know that $name and $NAME are two different variables to the shell.

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

$ echo $PS1

\$

The backslash character \ indicates that any other character that follows it should be interpreted exactly as it is and not processed by the shell. It is what we call a metacharacter.

It is common for the default bash command prompt to come in the format:

\u@\h:\W\$

Commands and variables in Linux are case-sensitive.

Each of these characters is interpreted specially. The \u is used to represent the username, the \h is used to represent the system name (hostname) and the \W is the current directory. An example for this prompt is:

uira@notebook:home$

PATH Variable

Another important Shell variable is PATH. The path stores a list of directories that contain programs that you can execute without needing to pass the full path to their location on the command line.

$ echo $PATH

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

It is important for you to know that the bash command interpreter follows this order to find and execute typed commands:

1)    Is the typed command a built-in command of the command interpreter?

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

3)    Was the command location explicitly declared?

An interesting tip is to include ":." at the end of the PATH variable so that bash includes the current directory in its search list for executable programs. Unlike MS-DOS, the current directory is not included in the default search list.

Without including ":." in PATH, it is necessary to inform the relative path when calling programs in the current directory with "./programname".

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 following commands:

$ LIVRO="Certificação Linux"

$ export LIVRO

Preferably variables should be declared in uppercase and do not put spaces between the variable name, 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 and Double Quotes in Linux

When the text of a variable is a common sequence of letters and numbers, it matters little whether you use single or double quotes.

$  FRASE1="Este é um teste"

$  FRASE2='de direfença entre aspas'

$ echo $FRASE1 $FRASE2

This is a test of difference between quotes

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

$ echo "$FRASE1 $FRASE2"

This is a test of difference between quotes

$ echo '$FRASE1 $FRASE2'

$FRASE1 $FRASE2

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

This makes a difference if you want, for example, to include a directory in the 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:/ora/oracle/admin/bin"

$ echo $PATH

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

In this case single quotes would not work.

Exporting Shell Variables for Use in Programs

After creating a shell variable, you need to export it to the environment using the export command.

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

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

This way, the child process (the program we want to execute) will inherit from the parent process (the shell) the created variables.

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

$  LIVRO="Certificação Linux"

echo $LIVRO

Certificação Linux

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

$ bash

$ echo $LIVRO

Some words cannot be used as variables, because they are what we call Bash reserved words, used as built-in 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, foreach, 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

&list=PL6IznNGWCdD89jP8kiacplFQcJlmMmjhb&index=91

Usage:

$ set [variable]

The set command displays a list of all local variables, environment variables, and shell functions.

Some options of the set command change the behavior of bash, as follows:

  • -C Prevents a program's output using `>', `>&' and `<>' from overwriting files. Same as the -o noclobber option
  • -n Reads commands but does not execute them. Useful for checking scripts. Same as the -o noexec option
  • -P Prohibits the shell from following symbolic links. Same as the -o physical option
  • -a Marks modified or created variables for export. Same as the -o allexport option
  • -o history Enables command history logging.

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

unset command

Usage:

$ unset [variable]

The unset command removes an environment variable from memory.

E.g.:

$ unset LIVRO

env command

Usage:

$ env VARIABLE=value program

The env command is used to run a program while passing an environment variable. It enables a specific program to read a variable without needing to export it with the export command. The -i option tells env to ignore the inherited environment, without changing the contents of any existing variable. It is useful for temporarily changing a variable for testing.

&list=PL6IznNGWCdD89jP8kiacplFQcJlmMmjhb&index=22

E.g.:

$ env HOME=/home/guest2 programax

pwd command

Usage:

$ pwd

The pwd command prints the current working directory.

E.g.:

$ pwd

/usr/local

&list=PL6IznNGWCdD89jP8kiacplFQcJlmMmjhb&index=80

Want to know if a certification is worth it? Learn why salaries are good, and why companies are looking for Linux professionals.

You will understand that the benefits far outweigh the sacrifice.

And if you have already decided, check out our Certification Guide.

And if you want to know where to take the exams, check the city list.

If you want to know the exam language, see this post.

Learn much more about Linux in our online course. You can enroll here with a 7-day free trial. If you already have an account, you can access here.

Like it? Share :-)

Uira Ribeiro

Prof. Uirá Ribeiro

Chair do Board do Linux Professional Institute

After years of watching professionals waste hours on simple tasks because they didn't know the right Linux tools, I decided to teach.
Today I'm the author of most of LPI's official Learning Materials and mentor to over 14,000 certified students.

See my full story →

That was just one piece. The course teaches the whole path — from your first command to exam day.

Certificação Linux — a plataforma líder em certificações Linux no Brasil
WhatsApp