Bash Variables: Useful Methods for Working with Variables in Bash
Bash variables are a foundational concept in shell scripting, allowing users to store and manipulate data efficiently within the Bash shell, a default in most Unix-based systems and VPS hosting environments.
In this tutorial, you’ll learn how to create, export, and use variables for automation and scripting.
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 essential when it comes to Bash scripting, making it easier to write complex functions and perform various operations. Users can store data such as numbers, strings, or arrays by creating variables.
Bash variables are case-sensitive, meaning myvariable
and MyVariable
are considered different 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
There are two main types of Bash variables: system-defined variables and user-defined variables.
System-defined variables (also known as environment variables) are pre-set by the operating system and can be accessed globally by all scripts. These variables provide information about the system and user environment.
Here are some common system-defined variables in Bash:
Variable | Example | Function |
SHELL | /bin/bash | Defines the name of the shell used |
PWD | /root | Shows the current working directory |
LOGNAME | root | Defines the logged-in user name |
MOTD_SHOWN | pam | Defines the message of the day for the system |
HOME | root | Home directory of the user |
LS_COLORS | rs=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_CONNECTION | 185.185.185.185 54321 185.185.185.186 12 | SSH connection information [user IP] [user port] [Linux machine IP] [Linux machine port] |
LESSCLOSE | /usr/bin/lesspipe %s %s | Used to invoke input postprocessor |
TERM | xterm-256color | Defines the terminal type |
LESSOPEN | /usr/bin/lesspipe %s | Used to invoke input post processor |
USER | root | Name of the current user |
SHLVL | 1 | Displays the number of shell levels the current shell is running on top of |
SSH_CLIENT | 185.185.185.185 54321 12 | SSH client information [user IP] [user port] [Linux machine port] |
PATH | /usr/local/sbin | Defines the directories to be searched for bash to find a command |
SSH_TTY | /dev/pts/0_=/usr/bin/printenv | 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 are created and modified by users. They are specific to the script or command where they are defined.
Working With Variables in Bash
Bash allows you to define and manipulate variables both from the command line and within scripts. Let’s take a quick look at both examples:
Using variables in command-line
We will create a myuser variable and check which shell it is using.
Using variables in a 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
How to work with special variables
Bash scripting includes several special variables that provide useful information about the current script, system environment, or user inputs.
Some of the most commonly used special variables in bash include:
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 |
$0 | 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 |
$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
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
User-defined variables are typically local to the script or command and inaccessible to other processes.
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
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 are global and can be used by all scripts on the system. They are usually written in uppercase letters to distinguish them from user-defined 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
To share a variable across multiple shell sessions, use the export
command. This makes the variable accessible to child processes, allowing you to use environment variables in different contexts.
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"
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 change how Bash interprets variable values. 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"
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'
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 the 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.
Conclusion
Bash variables, whether local or environment, are essential for scripting and automation. By understanding how to define, export, and use these variables, you can enhance the efficiency of your scripts and automate tasks on your system. Explore more by diving into the official Bash documentation or experimenting with Bash in your terminal.
If you have questions or want to share your experience, leave a comment below.