Variables are essential if you want to write scripts and understand what code you want to cut and paste from the web on your Linux computer. We'll get you started!
Variables are named symbols that represent either a string or a numeric value. If you use them in commands and expressions, they are treated as if you had entered the value they contain instead of the name of the variable.
To create a variable, simply specify a name and value. Your variable names should be descriptive and remind you of the value they have. A variable name can not start with a number or contain spaces. It can, however, begin with an underscore. You can also use any mix of alphanumeric uppercase and lowercase letters.
Here we create five variables. The format is to enter the name, the equal sign
= and the value. Note that there is no space before or after the equal sign. Assigning a value to a variable is often referred to as Assigning a value to a variable .
We create four string variables and one numeric variable,
me = Dave  my_boost = Linux
him = Popeye
his_boost = Spinach
this_year = 2019
To display the value in a variable, use the
command echo . You must precede the variable name with a dollar sign
$ if you reference the value contained therein (see below):
echo $ my_name
echo $ my_boost
echo $ this_year  The "echo" command displaying the values of variables in a terminal window." width="646" height="167" src="/pagespeed_static/1.JiBnMqyl6S.gif" onload="pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);" onerror="this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);"/>
Let's use all of our variables at once:echoing "$ my_boost for me is $ as $ his_boost for him $ (c) $ this_year"
 The values of the variables replace their names. You can also change the values of variables. To assign a new value to the
my_boostvariable, just repeat what you did when you assigned the first value:my_boost = Tequila
If If you run the previous command again, another result is displayed:echo "$ my_boost is $ his_boost for $ his_boost for $ him (c) $ this_year"
You can that is, using the same command that points to the same variables and getting different results if you change the values contained in the variables.
We'll talk about citing variables later. At the moment, here are some things to keep in mind:
- A single-quoted variable
& # 39;is treated as a literal string, not a variable.
- Variables in quotation marks
"are treated as variables.
- To get the value of a variable, you must specify the dollar sign
- A variable without the dollar sign
$Specifies only the name of the variable.
You can also create a variable whose value matches an existing variable or taken from a number of variables Command defines a new variable named
drink_of_the_Year, and assigns to it the combined values of the variables
drink_of-the_Year = "$ my_boost $ this_year"
 Using Variables in Scripts
Scripts would be complete without variables permanently blocked. Variables provide the flexibility that makes a script a general rather than a specific solution. To illustrate the difference, here is a script that counts the files in the
/ dev directory.
Enter this into a text file and save it as
fcnt.sh (for "File count"):
#! / Bin / bash folder_to_count = / dev file_count = $ (ls $ folder_to_count | wc -l) echo $ file_count files to $ folder_to_count
Before you can run the script, you need to make it executable as follows:
chmod + x fcnt.sh
Enter the following to Run Run the script:
This returns the number of files in the
/ dev directory. Here's how it works:
- A variable named
folder_to_countis defined and contains the string "/ dev.
- Another variable with the name
file_countis defined. This variable gets its value from a command replacement. This is the command phrase between the brackets
$ (). Note that there is a dollar sign in front of the first bracket
$. This construct
$ ()evaluates the commands in parentheses and then returns their final value. In this example, this value is assigned to the variable
file_count. For the variable
file_counta value has been passed, which must be kept. It does not matter how the value was received.
- The command evaluated at command substitution executes a file list
lsfor the directory in variable
folder_to_countset to "/ dev". So the script executes the command "ls / dev"
- The output of this command is passed to the command
wc. The option
-l(line count) causes
wcto count the number of lines in the output of the command
ls. Since each file is listed on a separate line, this indicates the number of files and subdirectories in the / dev directory. This value is assigned to the variable
- The last line returns the result with echo.
However, this only works for the / dev directory. How can we let the script work with each directory? Only a small change is required.
Using Command Line Parameters in Scripts
Many commands, such as
wc use command-line parameters. These provide information to the command so that it knows what you expect from it. If you want
ls to work in your home directory and also display hidden files, you can use the following command, where the tilde
~ and the
-a (all) options are command line parameters:
ls ~ -a
Our scripts can accept command-line parameters. They are designated for the first parameter as
$ 1 for the second as
$ 2 and for the ninth parameter as
$ 9 . (In fact, there is also a
$ 0 that always contains the script.)
You can reference command-line parameters in a script just as you would with regular variables. Change our script as shown below and save it under the new name
#! / Bin / bash folder_to_count = $ 1 file_count = $ (ls $ folder_to_count | wc -l) echo $ file_count files to $ folder_to_count
This time, the variable
folder_to_count is assigned the value of the first command line parameter,
$ 1 .
The rest of the script works exactly as before. Instead of a specific solution, your script is now a general solution. You can use it in any directory because it is not hard-coded to work only with / dev. [19659006[Herebyhowtomakethescriptexecutable:
chmod + x fcnt2.sh
Now Try it with a few directories. You can first run "/ dev" to make sure you get the same result as before. Type the following:
./fnct2.sh / dev [19659011</fnct2sh/etc[19659011</fnct2sh/bin
You get the same result (207) files as before for the directory "/ dev". This is encouraging, and you get directory-specific results for each of the other command-line parameters.
To shorten the script, you can dispense with the variable
folder_to_count and reference only
] $ 1 as follows:
#! / Bin / bash file_count = $ (ls $ 1 wc -l) echo $ file_count files in $ 1
Working with special variables
$ 0 which is always set to the file name of the script. That way, you can use the script to print the name correctly, even if it's renamed. This is useful in logging situations where you want to know the name of the process that added an entry.
The following other special preset variables:
- $ # : How many commands line parameters were passed to the script.
- $ @ : All command-line parameters were passed to the script.
- $? : The completion status of the last run process.
- $$ : The process ID (PID) of the current script.
- $ USER - The user name of the user running the script.
- $ HOSTNAME : The hostname of the computer where the script is running.
- $ SECONDS : The number of seconds that the script was executed.
- $ RANDOM ]: Returns a random number.
- $ LINENO : Returns the current line number of the script.
You want to see everyone in a script, right? You can! Save the following as a text file named
#! / Bin / bash echo "There were $ # command line parameters" echo "They are: $ @" echo "Parameter 1 is: $ 1" echo "The script is called: $ 0" # Any old process so we can report the exit status pwd echo "pwd returned $?" echo "This script has the process ID $$" echo "The script was started by $ USER" echo "It's on $ HOSTNAME" Sleep 3 echo "It's been running for $ SECONDS seconds" echo "random number: $ RANDOM" echo "This is the line number $ LINENO of the script"
Type the following to make it executable:
chmod + x special.sh
Now you can do it with a bunch execute various command line parameters as shown below.
Bash uses environment variables to define and record the properties of the environment created at startup. Bash can easily access this information. For example, your username, locale, the number of commands your history file can contain, your default editor, and more.
Use this command to display the active environment variables in your bash session:
env | less
If you scroll through the list, you may find some that you can refer to in your scripts.
When a script runs, it is in its own process, and the variables used can not be displayed outside of this process. If you want to share a variable with another script started by your script, you must export that variable. We show you this with two scripts.
First save the following with the 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 produces two variables,
second_var and assigns some values. It prints them into 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 been changed.
The second script we use is
script_two.sh . This is the script that calls
script_one.sh . Type:
#! / Bin / bash # check their values echo "$ 0: first_var = $ first_var, second_var = $ second_var" # set 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 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
Now enter the following to start
 The following tells us the output:
- script_one.sh returns the values of variables that are alpha and bravo.
- script_two.sh returns the values of variables (alpha and bravo) as received.
- script_two.sh changes them to charlie and delta.
- script_one.sh returns the values of the variables, which are still alpha and bravo.
What happens in the second script remains in the second script. Copies of the variables are sent to the second script, but are dropped when the script exits. The original variables in the first script are not changed by anything that happens to the copies in the second script.
You may have noticed that scripts that reference variables are enclosed in quotation marks
". This allows variables to be referenced correctly so that their values are used when the line
If the value you assign to a variable contains spaces, they must be in quotation marks This is because Bash defaults to using a space as a separator.
Here is an example:
site_name = How-To Geek
Bash sees the space "Geek" indicates that a new command is starting It indicates that there is no such command and returns the line
echo indicates that the variable
site_name is valid nothing - not even the "how-to" text.
Try again with a quote marking the value like fol gt:
site_name = "How-To Geek"
This time it is recognized as a single value and assigned to
correctly] site_name variable.
echo is your friend
It may take some time for you to get used to replacing commands, queuing variables, and remembering when to insert the dollar sign.
Before pressing Enter and execute Try a series of bash commands with
echo before. That way, you can make sure that what happens will be what you want. You can also catch errors that you may have made in the syntax.