Welcome to the second chapter of BASH scripting series in which we will discuss variables in bash. Did you know that every programming language has a way to let programmers declare variables in their programs? But what exactly are they and why do we need variables in programming? Please read on below to learn more about variables.
Table of Contents
What is a variable?
In computer programming, a variable is a named storage location which contains a value.
Literally, a variable is like an empty bowl that can hold something. That “something” is usually:
- an integer number like 123
- floating point number like 123.1
- a character like ‘z’
- or string of characters as in “Hello!”
Variables in BASH
A bash variable is declared by starting with dollar symbol “$” and then typing out its identifier name. Below is a sample variable named “variable” –
$variable But if you happen to declare a variable and assign some value to it at the same time, you’ll have to omit the “$” symbol as in: variable=123 Prefixing the “$” symbol to such (defined) variables would result in an error when you try to run your program.
It might seem confusing at first but you’ll get used to it after going through some example scripts afterward.
Rules to follow
BASH has some naming conventions or rules to declare a variable:
- A variable name cannot contain any special characters other than underscore “_”
$@variable or $vari%ble is incorrect
$_variable or $var_able is correct
- A variable name can contain number(s) but cannot start with it
$1variable is incorrect
$var1able is correct
Apart from the above two somewhat-strict rules, in case if you are working on environment variables then there is a standard practice of using all uppercase letters as the variable identifier name. Don’t worry if you didn’t get that part. You’ll soon do as we progress on with the following chapters to come.
Purpose of variable
OK, so we’ve gone through some of the variable concepts in BASH but why do we really need them. What exactly is their purpose for holding values?
Variables to the computer are like stored memories in a huge memory storehouse (ie., RAM), a way to retain information from it just like we humans have a way of memorizing stuff and retaining ’em by citing.
Variables store data either temporarily or permanently. A variable definition such as variable=123 is an example of a temporary-stored variable ie., we can change that value 123 to another if we want. However, there will be some cases where values for certain variables remain fixed such as the value of PI in mathematics. Those variables are declared as constants and their value cannot be changed again once already set.
Below are three example scripts you can try it out on your computer. So turn up your favorite text editor program, type in the sample scripts and save it in the bash directory we created in the Introduction chapter. Then launch your terminal program and change to the bash directory using the cd command. We will use the terminal to execute the example scripts.
After you’re done typing and saving a script, use the below command to execute your script on the terminal program –
This program will simply store a number value ie., 123 to the variable named “number” and then print it out on the screen.
#!/bin/bash number=123 echo $number
echo is a command that displays whatever string follows after it as output. And since we don’t want to print “
number” as output on the console screen but its value.
We prefixed it with “
$” symbol to tell
echo that number is a variable and not a string.
Compute and store
This program is somewhat realistic because most of the real-life program works this way.
Compute or execute the right-hand side and then store the result to the left-hand side.
#!/bin/bash readonly x=2 readonly y=2 let sum=$x+$y echo $sum
In the above program, we have two new commands used: readonly and let.
readonly is a way to tell the computer that variables
y are constants. So their values 2 are permanently stored and cannot be changed.
let is used to compute a mathematical expression on the right-hand side (in our case it’ll compute the sum of variables x and y) and then store the result to the left-hand side. Without let keyword, if we just type in
sum=$x+$y, we’ll get
2+2 as output and not
Get user input and store
The program will ask for user input (to enter some number), store the number to a variable, and then display it on the terminal screen.
#!/bin/bash echo Enter some number: read number echo The number you entered is $
Above we have another new command called read which is responsible for getting input from the user. Without read command, the program would execute to the end without asking and waiting for your (user) input.
Remember, a variable is a named storage location which contains a value. The value could be stored either temporarily or permanently in BASH. This wraps up our variable lesson in BASH scripting. And by the way, make sure to practice the example scripts so you can better grasp variable concepts before moving on to the next chapter. In our next chapter, we will learn about comments in BASH.
Frequently Asked Questions
What are variables in bash?
In Bash, variables are used to store data that can be used or manipulated by a script or program. Variables can hold various data types, including strings, numbers, arrays, etc.
How do you set variables in bash?
In Bash, you can set a variable by using the following syntax –
variable_name is the name of the variable and
value is the value you want to assign to it. Note that there should be no spaces around the equals sign
For example, to set a variable named
name to the value “John”, you can use the following command:
You can also assign the output of a command to a variable using command substitution, which is done by enclosing the command in
In this example, the output of the
pwd command (
which prints the current working directory) is assigned to the
You can also set variables to empty values by simply not providing a value after the equals sign:
Finally, note that variable names can only contain letters, numbers, and underscores and cannot begin with a number. Using all capital letters for environment variables to differentiate them from regular variables is also recommended.
What are the different types of variables in bash?
In Bash, there are several types of variables, including –
Local variables: These are defined and used only within the current shell or script. The current shell can access them only, or any child processes it spawns.
Environment variables: These are variables set for the entire system and can be accessed by any process or script running on the system. Environment variables are typically used to store configuration information, such as the PATH variable, which specifies the directories that contain executables.
Shell variables: These are variables set and maintained by the Bash shell. Examples include the PS1 variable, which specifies the command prompt, and the IFS variable, which specifies the input field separator.
Positional parameters: These variables hold the values of command-line arguments passed to a script or function. For example, the variable $1 holds the first argument, $2 holds the second argument, and so on.
Special parameters: These are variables that have a special meaning to Bash. Examples include $? which holds the exit status of the last executed command, $$ which holds the process ID of the current shell; and $! which holds the process ID of the last background command.
Array variables: These can hold multiple values under a single variable name. Bash supports indexed arrays (where values are accessed using numerical indices) and associative arrays (where values are accessed using string keys).
Overall, understanding the different types of variables in Bash can help you write scripts and programs that are flexible, robust, and easy to maintain.