fbpx Linux Shell Variables: Create, Modify and Use in Terminal | Certificação Linux

Linux Shell Variables: Create, Modify and Use in Terminal and Scripts

📅 01/01/2019 ⏱ 7 min ✍️ Uira Ribeiro
Linuxcommands
Linux Shell Variables: Create, Modify and Use in Terminal and 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

Even if you're not a programmer, you've probably heard of variables. They are a way the computer has to store values, whether they're numbers or a set of letters, so that they can be used later for some processing.

The Linux shell also allows users to create variables to store values, numbers, names, dates, and even the output of commands.

Various system settings are stored in variables, which can be changed at any time, allowing system customization.

PS1 Variable of the Linux Shell Prompt

The user's first contact with the Linux shell is the command prompt.

How this command prompt displays can vary across distributions, from the simplest with just a "$" to showing user information, server name, and even the current directory:

[uira@server1 ~]$

The command prompt can be customized through the configuration of a variable that the Linux shell maintains called PS1.

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

The first variable we will cover is the PS1, or simply Prompt String 1.

This variable stores the content of the bash command prompt when it is ready to receive commands.

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

By convention, variables are all written in uppercase. But it's important that you know that $name and $NOME are two different variables for the shell.

How to View the Content of a Variable?

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

$ echo $PS
\$

The 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 in a special way.

The \u is used to represent the username, \h is used to represent the system name (hostname), and \W is the current directory.

An example for this prompt is: uira@notebook:home$

The $PATH Variable

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

$ echo $PATH
/sbin:/bin:/usr/sbin:/usr/bin

It's important that you 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 standard search list. Without including ":." in PATH, it is necessary to enter the relative path when calling programs in the current directory with "./programname".

This is a problem for new Linux users who don't understand why typing a command or trying to run a program that is in the current folder doesn't work most of the time. Simply put, it's the missing ":." in $PATH.

The set Command to View or Change Variables in Linux

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

$ set

You can also change or create a new shell variable with the command:

$ LIVRO=”Certificação Linux”

Variables should preferably 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 or Double Quotes in Linux

When the text of a variable is a common sequence of letters and numbers, it doesn't matter much if you use single or double quotes.

$ FRASE1=”Este é um teste”
$ FRASE2='de direfença entre aspas'
$ echo $FRASE1 $FRASE2
Este é um teste de diferença entre aspas

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

$ echo “$FRASE1 $FRASE2”
Este é um teste de diferença entre aspas
$ 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 a Variable in the Shell

After creating a shell variable, it needs to be exported to the environment with 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 you run in bash).

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

Thus, 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 child processes:

$ bash
$ echo $LIVRO

Use of Wildcards

When working with files and directories in the shell, it's very common to need to work with multiple files at once. To make this type of task simpler, Linux offers the wildcard feature for file and directory names.

Just like in a deck of cards, wildcards are symbols that can mean many things. In Linux, they allow you to use them as part of file and directory names. See the table below:

SymbolDescription
*Means "matches anything" and can substitute one or more characters in a name. For example, "Certifi*" can mean "Certificado", "Certificação" or any other combination of filenames that start with "Certifi".
?Means that it can substitute only one character in a name. For example: "?ertificado" can  replace "Certificado", "certificado" or any other combination of filenames that start with any character and end with "ertificado".
{text1, text2...}Replaces the part inside the braces with text1, then with text2, and so on. For example: "part_{a,b,c}" will result in "part_a", "part_b" and "part_c".

Examples:

$ ls *.txt

Lists all files with the .txt suffix

$ cat doc??? >> documentos

Concatenates all files starting with "doc" that have 6 characters in size into the documentos file.

There are also special variables in Linux, used for creating shell scripts.

Conclusion

If you need to store some value or data to be used later, variables are essential. And you need to know the main shell variables in Linux, like PS1 and PATH.

Learn much more about Linux in our online course. You can enroll here. If you already have an account, or want to create one, just log in or create your user here.

Liked 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