Jan 16, 2024
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 hosting).
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:
|Defines the name of the shell used
|Shows the current working directory
|Defines the logged-in user name
|Defines the message of the day for the system
|Home directory of the user
|Used to set the colors the filenames will be displayed for the user
|188.8.131.52 54321 184.108.40.206 12
|SSH connection information [user IP] [user port] [Linux machine IP] [Linux machine port]
|/usr/bin/lesspipe %s %s
|Used to invoke input postprocessor
|Defines the terminal type
|Used to invoke input post processor
|Name of the current user
|Displays the number of shell levels the current shell is running on top of
|220.127.116.11 54321 12
|SSH client information [user IP] [user port] [Linux machine port]
|Defines the directories to be searched for bash to find a command
|Displays 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.
- 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:
We will create a myuser variable and check which shell it is using.
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:
Then, paste the following contents:
#!/bin/bash myuser="mylovelyname" echo my user is $myuser and my shell is $SHELL
Lastly, run the script:
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:
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:
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:
|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
|Displays 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
|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:
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
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:
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
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"
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:
Now, if you were to print this variable, it would work just fine:
Now, use the export command to export the hello variable and switch out to a new shell instance:
export hello bash echo "$hello"
For example, if you would’ve skipped the export command, no output would be visible:
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:
Now, paste the following:
#!/bin/bash doublequotes="I like writing command-line arguments" echo "Double quotes work like this: $doublequotes"
Then, create another bash script:
Finally, use the following command:
#!/bin/bash singlequotes="String variables are the best" echo 'Single quotes work like this: $singlequotes'
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 10)
touch $(seq 1 10) $( ) substitution special characters allow the touch command to be run together, resulting in a command that creates 10 empty files.
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.