How To Use Variables in Bash Script (Simple Guide)

In this guide, we will cover how to use variables in bash script.

In Unix/Linux, if you want to automate the repetitive tasks then it is recommended to use bash script and if required schedule it via crontab. A bash script contains a setup commands, loops and variables.

Variables are the building blocks of the programming language. They allow us to refer to a memory location using a name. With help of variables, we can assign, read, and manipulate values stored at a particular memory location. In addition to this, carefully chosen variable names improve the readability of the program.

Variable Naming Rules and Conventions

Like other programming languages, there are some rules and conventions that need to be followed while working with variables in bash.

Let’s discuss the rules first:

  • A variable name can only have alphanumeric characters (letters and digits) and underscore
  • Variable name must start with either a letter or an underscore character
  • Variable names are case-sensitive. It means msg and MSG are totally two different variables

The conventions are not rules but these are widely accepted best practices. Let’s discuss the conventions related to variable naming:

  • All variables are defined using the UPPER-CASE letters
  • An underscore character is used to improve readability. For example, a variable FIRST_NAME is more readable than FIRSTNAME

Working With Variables

In this section, we will see how to assign and display the value of a variable. Then we will see how to unset the value of a variable. Finally, we will see how to create a write protected variable.

We can assign a value to a variable using an assignment operator as follows:

$ MSG="Hello, World"

We can use the Dollar($) symbol with a variable to print its value:

$ echo $MSG
Hello, World

Additionally, we can also use the assignment operator to overwrite the value of the variable:

$ MSG="New Value"
$ echo $MSG
New Value

In bash, we can use the unset command to clear the value of the variable. Let’s see this with an example:

$ echo $MSG
New Value
$ unset MSG
$ echo $MSG
$

In the above output, the last line is blank which represents a variable without a value. Please note that, we should not use a Dollar($) symbol with the unset command.

In a larger script, we often see that many variables are used. Remembering the name and location of every variable is an impossible task. In such cases, there are chances that someone might overwrite an existing variable inadvertently. To avoid such scenarios, we can use the readonly command to make the variable write-protected.

$ MSG="Read-only message"
$ readonly MSG
$ echo $MSG
Read-only message

Now, let’s try to modify the MSG variable and observe the behavior:

$ MSG="Modified message"
bash: MSG: readonly variable

The operation failed as expected with a read-only variable error.

Exporting a Variable

In bash, by default variables are scoped to the current process only. It means the variable defined in the parent process is not visible to its children by default. Let’s understand this with an example:

First, define a new variable and print its value:

$ MESSAGE="Hello, World"
$ echo $MESSAGE
Hello, World

Now, let’s launch another instance of the bash shell and print the value of the same variable:

$ bash
$ echo $MESSAGE
$

In the above output, we can see that the value of the variable is empty.

To overcome this limitation, we can use the export command. This command makes the parent process’ variables visible to their children.

To understand this, we need to perform the following operations in order:

  • Exit from the child’s shell
  • Export variable in the parent shell
  • Launch a new instance of the bash shell as a child process
  • Print value of the variable

Export-Variables-in-bash-script

Here, we can see that the child process can see the parent process’ variable.

Storing Command’s Output to a Variable

Sometimes, we need to store the command output in the variable. In such scenarios, we can either use a Backquotes(`) or command substitution operator. With this approach, the shell executes the command first and then stores the output in a variable.

$ CUR_DIR=`pwd`
$ echo "Current directory = $CUR_DIR"
Current directory = /tmp

We can achieve the same result using the command substitution operator as well:

$ CUR_DIR=$(pwd)
$ echo "Current directory = $CUR_DIR"
Current directory = /tmp

Variable Types

In bash, there are three types of variables:

User Defined Variables

These variables are created by the user explicitly. The variables which we created in previous sections are examples of user defined variables. The scope of this variable is limited to the current process and its children only.

System Defined Variables

Users don’t create these variables. Instead, these variables are created by the Operating System(OS) itself. Unlike user defined variables, these variables are available to each and every process running on the system.

Some of the commonly used variables of this type are – PWD, USER, SHELL, HOSTNAME, etc.

We can use the env command to list all system defined variables:

$ env

The above command generates the following output:

System-Defined-Variables-env-Command

Special Variables

As the name suggests these are the special variables used by the bash. These variables are available to all the users of the system.

Let’s see the some of the commonly used special variable in the bash:

Find the Current Process Name

We can use the $0 variable to find the name of the current process. Let’s find the name of the current shell using this:

$ echo $0
bash

Now, let’s change the shell and execute the same command again:

$ sh
$ echo $0
sh

If we execute the same command from the script then it prints the script name.

Find the Exit Status of the Command

We can use the $? variable to find the exit status of the last executed command. The zero value represents the successful whereas the non-zero value represents the unsuccessful command execution.

Let’s run the command which can be executed successfully and observe the return value:

$ ls -d /tmp/
/tmp/
$ echo $?
0

Now, let’s run the command which will generate an error:

$ ls non-existing-file
ls: cannot access 'non-existing-file': No such file or directory
$ echo $?
2

In the above examples, we can see that the ls command returned zero for the existing directory and non-zero for the non-existing file.

Find the Process ID of the Current Shell

We can use the $$ variable to find the process id of the current shell. Let’s find the process id of the bash using this:

$ echo "Process ID of the current shell = $$"
Process ID of the current shell = 16504

Let’s verify that the result is correct using the pgrep command:

$ pgrep bash
16504

Conclusion:

In this guide, we discussed how to create and use variables. Then we saw how to store command output in the variable. Finally, we discussed the different types of variables available in the bash.

1 thought on “How To Use Variables in Bash Script (Simple Guide)”

Leave a Comment

10 − three =