How to Work with Variables in Bash

A Linux terminal with green text on a laptop.Fatmawati Achmad Zaenuri / Shutterstock

Variables are essential if you want to write scripts and understand what the code you are going to copy and paste from the web will do to your Linux computer. We will help you get started!

Variables 101

Variables are named symbols that represent a string or numeric value. When you use them in commands and expressions, they are treated as if you entered the value they contain instead of the variable name.

To create a variable, just give it a name and a value. The names of your variables must be descriptive and remind you of the value they hold. A variable name can not start with a number, nor contain spaces. However, it can begin with an underscore. Apart from that, you can use any mixture of lowercase and uppercase alphanumeric characters.

Examples

Here we will create five variables. The format consists of typing the name, the equal sign = and the value. Note that there is no space before or after the equal sign. Giving a value to a variable is often referred to as assigning a value to the variable.

We will create four string variables and one numeric variable, this_year:

me = Dave
my_boost = Linux
him = Popeye
his_boost = Spinach
this_year = 2019

Five variables in a terminal window.

AT see the value held in a variable, use the echo command. You must precede the name of the variable with a dollar sign $ each time you reference the value it contains, as shown below:

echo $ my_name
echo $ my_boost
echo $ this_year

Let's use all our variables at the same time:

echo "$ my_boost is to $ me as $ his_boost is to $ him (c) $ this_year"

The values ​​of the variables replace their names. You can also change the values ​​of the variables. To assign a new value to the variable, my_boost, just repeat what you did when you assigned its first value, as follows:

my_boost = Tequila

<img class="alignnone wp-image-442342 size-full" data-pagespeed-lazy-src="http://howtodoeasily.com/wp-content/uploads/2019/10/How-to-Work-with-Variables-in-Bash.png" alt="the "my_boost = Tequila" variable in a terminal window. "width =" 646 "height =" 57 "src =" / pagespeed_static / 1.JiBnMqyl6S.gif "onload =" pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon (this); "onerror = "this.onerror = null; pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon (this);" />

If you restart the previous command, you now get a different result:

echo "$ my_boost is to $ me as $ his_boost is to $ him (c) $ this_year"

So you can use the same command that references the same variables and get different results if you change the values ​​stored in the variables.

We will talk about citing variables later. For the moment, here are some points to remember:

A variable in single quotation marks is treated as a literal string and not as a variable.
Quoted variables "are treated as variables.
To get the value of a variable, you must provide the dollar sign $.
A variable without the dollar $ sign provides only the name of the variable.

Correct and incorrect examples of referencing variables in a terminal window.

You can also create a variable that gets its value from an existing variable or from a number of variables. The following command sets a new variable named drink_of_the_Year and assigns it the combined values ​​of the variables my_boost and this_year:

drink_of-the_Year = "$ my_booster $ this_year"
echo drink_of_the-year

How to use variables in scripts

The scripts would be completely blocked without variables. Variables provide the flexibility that makes scripting a general rather than a specific solution. To illustrate the difference, here is a script that counts the files in the / dev directory.

Type this into a text file, then save as fcnt.sh (for "number of files"):

#! / bin / bash

folder_to_count = / dev

number_files = $ (ls $ account_folder | wc -l)

echo $ file_count files in $ folder_to_count

Before you can run the script, you must make it executable, as shown below:

chmod + x fcnt.sh

Type the following to run the script:

./fcnt.sh

This displays the number of files in the / dev directory. That's how it works:

is defined a variable called folder_to_count, and it is set to contain the string "/ dev. "
Another variable, called file_count, is defined. This variable gets its value from a command substitution. This is the command phrase between the $ () parentheses. Note that there is a $ dollar sign before the first parenthesis. This $ () construct evaluates the commands in parentheses and returns their final value. In this example, this value is assigned to the file_count variable. For the file_count variable, it passed a value to keep; he is not interested in how the value was obtained.
The evaluated command in the command substitution executes a list of ls files in the directory of the folder_to_count variable, set to "/ dev". The script runs the "ls / dev" command.
The result of this command is channeled into the wc command. The -l option (number of lines) causes the command wc count the number of lines in the output of the ls command. Each file is listed on a separate line, which is the number of files and subdirectories in the "/ dev" directory. This value is assigned to the file_count variable.
The last line uses echo to display the result.

But this only works for the "/ dev" directory. How can we make the script work with any directory? All it takes is a small change.

How to use command-line parameters in scripts

Many commands, such as ls and wc, take command line parameters. These provide information to order so that she knows what you want her to do. If you want ls to work on your home directory and also to show hidden files, you can use the following command, where tilde ~ and the -a (all) option are command line parameters:

ls ~ -a

Our scripts can accept command line parameters. They are referenced as $ 1 for the first parameter, $ 2 for the second, and so on. up to $ 9 for the ninth parameter. (In fact, there is $ 0, as well, but it's reserved to always hold the script.)

You can reference command line parameters in a script just as you would with normal variables. Let's modify our script, as shown below, and save it under the new name fcnt2.sh:

#! / bin / bash

folder_to_count = $ 1

number_files = $ (ls $ account_folder | wc -l)

echo $ file_count files in $ folder_to_count

This time, the folder_to_count variable is assigned the value of the first command line parameter, $ 1.

The rest of the script works exactly as before. Rather than a specific solution, your script is now general. You can use it on a directory because it does not hardcoded work only with "/ dev. "

Here's how to make the script executable:

chmod + x fcnt2.sh

Now, try it with a few directories. You can do "/ dev" first to make sure you get the same result as before. Type the following:

./fnct2.sh / dev
./fnct2.sh / etc
./fnct2.sh / bin

You get the same result (207 files) as before for the "/ dev" directory. This is encouraging and you get directory-specific results for each of the other command-line parameters.

To shorten the script, you can do without the variable, folder_to_count, and simply refer to $ 1, as follows:

#! / bin / bash

number_files = $ (ls $ 1 wc -l)

echo $ file_count files in $ 1

Working with special variables

We mentioned $ 0, which is always set to the script file name. This allows you to use the script to do things like print his name correctly, even if it is renamed. This is useful in logging situations, where you want to know the name of the process that added an entry.

Here are the other special predefined variables:

$ #: How many command line parameters have been passed to the script.
$ @: All command line parameters passed to the script.
$?: The exit status of the last process to execute.
$$: The process ID (PID) of the current script.
$ USER: The user name of the user running the script.
$ HOST NAME: The host name of the computer running the script.
$ SECONDS: The number of seconds of execution of the script.
$ RANDOM: Returns a random number.
$ LINENO: Returns the current line number of the script.

You want to see them all in one script, is not it? You can! Save the following in a text file called special.sh:

#! / bin / bash

echo "There were $ # command line parameters"
echo "They are: $ @"
echo "Parameter 1 is: $ 1"
echo "The script calls: $ 0"
# any old process to report on the status of exit
pwd
echo "pwd returned $?"
echo "This script has a process id $$"
echo "The script was started by $ USER"
echo "It turns on $ HOSTNAME"
to sleep 3
echo "It works since $ SECONDS seconds"
echo "Random number: $ RANDOM"
echo "This is the $ LINENO line number of the script"

Type the following to make it executable:

chmod + x special.sh

Now you can run it with a bunch of different command line parameters, as shown below.

Environment variables

Bash uses environment variables to set and save the properties of the environment created when it is launched. This hold information that Bash can easily access, such as your user name, your locale, the number of commands that your history file can hold, your default editor, and so on.

To see the active environment variables in your Bash session, use this command:

env | less

If you scroll down the list, you may find one that would be useful to reference in your scripts.

List of active environment variables in a terminal window.

How to export variables

When a script is executed, it is in its own process, and the variables that it uses can not be seen outside of this process. If you want to share a variable with another script started by your script, you must export that variable. We will show you how to do this with two scripts.

Start by registering the following under the script_one.sh file name:

#! / bin / bash

first_var = alpha
second_var = bravo

# check their values
echo "$ 0: first_var = $ first_var, second_var = $ second_var"

export first_var
export second_var

./script_two.sh

# check their values ​​again
echo "$ 0: first_var = $ first_var, second_var = $ second_var"

This creates two variables, first_var and second_var, and assigns values. It prints them in the terminal window, exports the variables and calls script_two.sh. When script_two.sh ends and the process returns to this script, the variables are printed again in the terminal window. Then you can see if they have changed.

The second script we will use is script_two.sh. That's the script that script_one.shcalls. Type the following:

#! / bin / bash

# check their values
echo "$ 0: first_var = $ first_var, second_var = $ second_var"

# define new values
first_var = charlie
second_var = delta

# check their values ​​again
echo "$ 0: first_var = $ first_var, second_var = $ second_var"

This second script prints the values ​​of the two variables, assigns the new values, and then prints them again.

To run these scripts, you must type the following to make them executable:

chmod + x script_one.sh
chmod + x script_two.sh

And now, type the following to start script_one.sh:

./script_one.sh

This is what the exit tells us:

script_one.sh displays the values ​​of the variables, alpha and bravo.
script_two.sh displays the values ​​of the variables (alpha and bravo) as they were received.
script_two.sh change them into charlie and delta.
script_one.sh shows the values ​​of the variables, which are always alpha and bravo.

What happens in the second script remains in the second script. It's like copies of the variables are sent to the second script, but they are discarded when we leave that script. The original variables in the first script are not modified by anything that happens to the copies in the second.

How to cite variables

You may have noticed that when scripts refer to variables, they are enclosed in quotation marks. "This makes it possible to correctly reference variables, so their values ​​are used when the line is executed in the script.

If the value you assign to a variable includes spaces, they must be enclosed in quotation marks when you assign them to the variable. Indeed, by default, Bash uses a space as a delimiter.

Here is an example:

site_name = Geek How-To

Bash sees the space before "Geek" as an indication of launching a new command. He reports that there is no such command and abandons the line. echo shows us that the site_name variable does not contain anything – not even the "How-To" text.

Try again with quotation marks around the value, as shown below:

site_name = "How-To Geek"

This time, it is recognized as a unique value and correctly assigned to the site_name variable.

echo is your friend

It may take some time to get used to ordering substitutions, citing variables, and remembering when to include the dollar sign.

Before pressing Enter and running a Bash command line, try it with echo in front. That way, you can make sure what's going to happen is what you want. You can also detect errors that you may have made in the syntax.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.