Bash Variables: Useful Methods for Working with Variables in Bash

Any programming language comes with its own set of variables. They are an essential part of any system and are needed to run even the most simple programs.

With variables, users can store any information, such as numbers or dates, as well as strings, such as answers to questions, alphanumeric characters, their name information, or even array elements.

Bash is no exception and also comes with variables. It’s a Unix shell that reads shell commands and uses them to interact with your physical computer or a virtual private server (VPS).

This tutorial will cover all the different types of bash variables and provide some practical examples of how you can use them on your machine.

What Exactly Are Bash Variables, and How Do They Work?

A bash variable acts as temporary storage for a string or a number. Bash variables are prevalent when it comes to bash scripting. Variables also make it easy for users to write complex functions and perform various operations.

Users can create variables by giving them a name and a value. A name can be anything. However, it cannot start with a number, and it cannot contain spaces, only underscores if necessary.

As for value, it can be any string or number. Keeping the variable name similar to its value is recommended, as it’s easier to remember and differentiate between other variables.

Here are a few other syntax caveats worth mentioning:

  • Even though it’s not possible to put numbers at the start of variables, users can still make the first or any characters in a variable name using capital letters.
  • Bash variables are case-sensitive, meaning that myvariable and MyVariable will be considered different variables.
  • When a user wants to refer to a variable, print it out. In other words, you need to add a $ symbol before its name. This way, bash will know that the user wants to use a variable value.
  • Whenever a user needs to create a variable or modify its value, the $ symbol is not necessary, just the actual name of the variable.
  • Usually, variable manipulation is used in bash scripts, loops, and arrays. However, it is possible to specify and use variables without scripts – simply state that in the command-line.

Types of Bash Variables

Bash comes in two types of variables – system-defined and user-defined variables. Let’s analyze them in greater detail:

  • System-defined variables – as the name suggests, bash already comes with a set of variables, which can also be called environment variables. All of them can be used by all bash scripts as they are already defined by the system itself:
Variable Example Function
SHELL /bin/bash Defines the name of the shell used
PWD/rootShows the current working directory
LOGNAMErootDefines the logged-in user name
MOTD_SHOWNpamDefines the message of the day for the system
HOMErootHome directory of the user
LS_COLORSrs=0:di=01;34:ln=01;36:mh=00:pi=40;Used to set the colors the filenames will be displayed for the user
SSH_CONNECTION185.185.185.185 54321 185.185.185.186 12SSH connection information [user IP] [user port] [Linux machine IP] [Linux machine port]
LESSCLOSE/usr/bin/lesspipe %s %sUsed to invoke input postprocessor
TERMxterm-256colorDefines the terminal type
LESSOPEN/usr/bin/lesspipe %sUsed to invoke input post processor
USERrootName of the current user
SHLVL1Displays the number of shell levels the current shell is running on top of
SSH_CLIENT185.185.185.185 54321 12SSH client information [user IP] [user port] [Linux machine port]
PATH/usr/local/sbinDefines the directories to be searched for bash to find a command
SSH_TTY/dev/pts/0_=/usr/bin/printenvDisplays path to the device associated with the current shell or command

Users can always check the list of system-defined variables using env or printenv commands.

The printenv command output in the command line. It displays all of the global variables, as well as some other programming languages that do not come with global variables, one of them being Java. In bash, users have access to plenty of system variables that can display such important information as SHELL type, user home directory, or information about the current SSH session
  • User-defined variables – these are variables set and modified by the user. They can also be called local variables and are only visible within the block of code. Unlike environment variables, user-defined variables only work for that particular script.

Working With Variables in Bash

Bash allows users to define and manipulate variables in both bash scripts and the command-line. Let’s take a quick look at both examples:

Command-line

We will create a myuser variable and check which shell it is using.

The use of local variables combined with the system-defined variable that displays the SHELL type

Bash script

A more convenient way to manipulate variables is with the help of a bash script. We will create the same script in the command-line but using a bash script. Start by creating a bash script file with your preferred text editor:

nano myscript.sh

Then, paste the following contents:

#!/bin/bash
myuser="mylovelyname"
echo my user is $myuser and my shell is $SHELL

Lastly, run the script:

bash myscript.sh
The use of two variables in a terminal window. Output ends when an echo shows the results

How to Use Variables in Bash Scripts

One of the most popular uses for bash variables is in bash scripting. Users can define all sorts of variables and use them in automated scripts.

When executed, such scripts can perform thousands of operations with a single click, making them especially useful for automation tasks or to save time writing similar commands manually.

Let’s start with a simple example. Begin by creating a script with your favorite text editor. We will use nano in this case:

nano script.sh

Then, paste the following contents:

#!/bin/bash
myvariablename="I love programming languages and variable declaration"
echo $myvariablename

The first line defines the shell we will use. In our case, it will be a bash shell.

Then, the script will create a new variable named myvariablename. Mind that in order to assign a new variable, you will need to use an equals sign (=).

We will use the echo command to print out the variable value. We also need to use a dollar sign ($), so the bash knows we need variable value.

Lastly, run the script using this bash command:

bash script.sh
The terminal window displaying on how to assign a particular value to a variable in bash

As shown in the example above, the command executes the whole script, and bash performs all user-specified actions on the system.

How to Work With Special Variables

Bash comes with various special characters, also called special variables. The following table will cover all of them:

Special variable Explanation
$@ Stores arguments as an array
$$Displays the process ID of the current shell
$#Show the number of arguments supplied in a given script
$*Groups all given arguments by connecting them together
$!Shows the ID of the last background job
$?Displays the exit status code for the latest executed command
$0Displays the filename of the current script
$_Sets the variable to the latest argument of the last command
$-Displays the currently used flags on bash shell
$1-${11}Store data of the first 11 argument names

Let’s use some of these special characters and make an example script out of it. Start by creating a script file:

nano specialcharacters.sh

The following code will showcase the functionality of $0, $*, and $$ special variables:

#!/bin/bash
#Create a new variable
myvariable="Writing command-line arguments are fun"
#Connect variables with double quotes
echo "I am" "a variable" "in bash"; $*
#Display the process id of the current shell
echo $$
#Display the filename of this script
echo $0
#Print out myvariable value
echo $myvariable
The terminal window shows the use of a few special characters in bash

First, we declared a new variable, then used the first parameter to connect the strings with double quotes into one. We then used the remaining special characters to display the ID of the current shell and the shell file name we executed.

How to Create Your Bash Variables

Any variable you create other than environment variables is considered your own. In other words, it will only work within your script.

Note that variables cannot start with a number or contain spaces. However, underscores and capital letters are allowed. Let’s create an example bash script with different types of variable names:

nano differentvariables.sh

Then, paste the following:

#!/bin/bash
variablename="Local variables in bash are awesome"
Variablename="Numeric values are also allowed 123"
VariableName="4 5 6"
Variable_Name="Setting variables are fun"
Variable_Nam3="Bash also performs word splitting so any spaces will be removed 1    2   3  4"
echo $variablename
echo $Variablename
echo $VariableName
echo $Variable_Name
echo $Variable_Nam3
The current script on the terminal displays the majority of valid variable names

Our example shows that even if the variable names are similar, they are all interpreted as separate variables.

How to Work with Environment Variables

Environment variables can be used by all bash scripts on a given system. Unlike local variables, environment ones are automatically set by the system. They are always written with capital letters, which is one of the main indications that users are using environment variables.

For example, the following script will display four essential parameters that system administrators can use when managing systems: shell type, user current working directory, home directory, and actual user name.

#!/bin/bash
echo "This user is using $SHELL shell"
echo "Their working directory is: $PWD"
echo "While their home directory is: $HOME"
echo "And the user name is: $USER"
The terminal window showcases the commands to display user's shell type, their working and home directories, and their user name

How to Export Bash Variables

Exporting variables in bash allows users to use such variables between different child shell instances. In order to export variables, first, we need to create a test variable:

hello=world

Now, if you were to print this variable, it would work just fine:

echo "$hello"
Variable declaration in a terminal, echo command prints out the variable value

Now, use the export command to export the hello variable and switch out to a new shell instance:

export hello
bash 
echo "$hello"
Export command use case in a terminal. It allows users to use locally defined variables within different shell instances

For example, if you would’ve skipped the export command, no output would be visible:

Terminal output when the export command wasn't used. In this case echo command gives out no output for the user

How to Quote Bash Variables

Quotation marks play an essential role in the bash shell. Depending if you use double quotes (“) or single quotes (‘), it can change the output.

For example, we will create two scripts, one using double quotes and the other one using single quotes. Start making the bash script by pasting the following command:

nano doublequotes.sh

Now, paste the following:

#!/bin/bash
doublequotes="I like writing command-line arguments"
echo "Double quotes work like this: $doublequotes"
The terminal shows the use case of double quotes, in that case, the user will see a standard output where bash will print out the actual value of a given variable

Then, create another bash script:

nano singlequotes.sh

Finally, use the following command:

#!/bin/bash
singlequotes="String variables are the best"
echo 'Single quotes work like this: $singlequotes'
The terminal window shows the second script containing single quotes, in this case, bash will print out the original variables' names instead of values

Double quotes print out the actual variable value, as seen in the examples. In contrast, single quotes show only the variable name instead.

How to Use Substitution Command on Bash

Command substitution, also known as variable substitution, is the process of allowing a command to run and its output to be pasted back as command-line arguments.

For example, let us use substitution to create 10 files with the help of a sequence command and $( ) special characters:

touch $(seq 1 5)

touch $(seq 1 5) $( ) substitution special characters allow the touch command to be run together, resulting in a command that creates 10 empty files.

Conclusion

As with most programming languages, bash comes with its own variables, classified as local and environment variables. Users can use them to create scripts to automate tasks or perform several other actions on the bash shell.

In this tutorial, we’ve covered all the different types of variables and provided some useful examples of how they can be used in real-life scenarios on your physical or virtual servers.
We hope that you found this tutorial helpful. If you have any questions or insights, leave them in the comments section below.

Author
The author

Ignas R.

Ignas is a Technical Content Writer at Hostinger. After helping people tackle even the most complex technical issues as a Customer Success Specialist, his current goal is to write easy-to-follow articles so that these issues will not happen at all. During his free time, Ignas likes to play video games and fix up things around his house.