In Bash scripting, storing the output of a command is a fundamental task. The task includes command substitution and variable assigning techniques. One can substitute commands using dollar signs or backticks. Later, assign the output to a variable. After assigning the variable, one can reference and utilize it throughout the script as needed. In this article, I will show you how to set the output of a command to a variable in Bash script.
2 Methods of Setting Output of Command to Variables in Bash Script
There are two common methods of setting the output of the Bash command into a variable. Command within a dollar sign or within a backtick is executed and stored in a variable.
1. Substituting Command and Set in a Variable Using Dollar Sign
In this first method, I will discuss substituting a Bash command using the dollar sign ($) and storing the output in a variable for further use in a script.
A. The Output of a Single Command
In the following example, I will store the output of the pwd command and use it later in the script. Let’s see the bash script for this:
#!/bin/bash
dir=$(pwd)
echo "Your current directory: $dir"
This simple program echoes the current directory path that is stored in the dir variable. Previously, the pwd
command is used to get the current directory path.
The output image shows the current directory as expected.
B. Command With Formatting
A Bash Command might have different options and arguments. The output of the command significantly varies based while using those options. In this script, I am going to show how to format command output with options and store the output in a variable. For that, write the following script:
#!/bin/bash
today=$(date +"%d %B") # Get today's date and store it in today variable
if [[ "$today" == "25 December" ]]; then
echo "Merry Christmas! Today is a special day of celebration!"
else
echo -e "Today is $today.\nEnjoy the day."
fi
This script uses the date
command to get the current date and stores the output in the today variable. The format of the date stored in the variable is defined using +"%d %B"
. Here, %d
represents the day of the month, and %B
represents the full month name.
The script then checks if today’s date is December 25th using the condition [[ "$today" == "25 December" ]]
. If the condition is true, it echoes “Merry Christmas! Today is a special day of celebration!”.
If the condition is false, it executes the else block. The -e
option enables the interpretation of backslash escapes to display a newline character between the two lines.
When running the script it shows today’s date with the dd/mm format.
C. The Output of Multiple Commands With Options and Arguments
In Bash script, multiple commands can be used for various purposes in a single line. In this example, I will show you how to set the output of multiple commands in a variable. And later use that variable for more complex tasks.
#!/bin/bash
count_files=$(find . -type f -print | wc -l)
echo "There are $count_files files in the current working directory."
empty_files=$(find . -type f -empty | wc -l)
echo " $empty_files of them are empty."
Here, the wc command initially counts the number of total files in the current directory when the output of the find command passes through it. The overall output is set to the count_files variable. Later, the -empty
option of the find
command counts the empty files of the current directory. Each time the number of counted files is echoed using the echo
command.
When running the code, it shows the total files of the current directory and how many of them are empty.
2. Substituting Command and Set in a Variable Using Backtick
Command substitution using backticks (` `) is an older method to capture and store command output in a variable. The command within backticks is the desired command to execute and retrieve the output.
If our scripts have to be really portable on various Unix systems along with Bash or KornShell, it’s better to use backticks notation rather than the dollar sign. To explore further regarding command substitution using backtick, write the following script:
#!/bin/bash
current_user=`whoami`
echo “The logged in user is: $current_user”
This script will execute whoami within backtick and store the output in the current_user variable. It echoed back the user name when executing the echo
command.
The image shows the current logged in user after successfully substituting the whoami command.
A. Multiline Command Substitution Using Backslash
Backslash is used for writing multiline commands in Bash script. To work on it open a file and write the following script:
#!/bin/bash
info=`(grep -l\
-i -n -w\
"hidden" *.txt)`
echo $info
This will search for the word “hidden” (case-insensitive and whole word match) in all the .txt files in the current directory. It will then print the filenames of the matching files along with the line numbers where the word “hidden” is found. Here, slash (\) is used for each new line of command substitution.
The output shows that there is a file named message.txt that contains the word hidden.
Note: Nested backticks often don’t work in Bash. Hence not recommended. For example, the following script will show an error.
#!/bin/bash
`cat `(grep -l\
-i -n -w\
"hidden" *.txt)``
The script shows an error due to the nested backtick that can not be executed.
B. Substituting Command With Path Name
Like substituting a command using its name one can easily substitute the command using its path name as well. To see how it works, open a file & write the following script:
#!/bin/bash
dirname=`/bin/pwd`
echo “Current directory:$dirname”
This script prints the current directory. Initially, it substitutes the pwd
command using the backticks and the pathname of the command. Later it echoed the current directory that is stored in the dirname variable previously.
Comparative Analysis of Methods to Set Command Output to Bash Variable
In this article, I have discussed two different methods of substituting commands. Here is a comparative analysis of these two methods:
Method | Advantage | Disadvantage |
---|---|---|
Dollar substitution |
|
|
Backtick substitution |
|
|
I find dollar substitution to be straightforward and simple. On the other hand, nested backticks can be confusing and prone to errors. Therefore, if you don’t specifically require the use of backticks, dollar substitution would be a better choice.
3 Practical Cases of Setting Output of Command to Variables in Bash Script
There are various scenarios where it is useful or necessary to store the output of a command in a variable. In the following examples, I will discuss three common use cases where storing command output can be beneficial.
1. Disk Usage of Current Directory
To visualize the disk usage of the current directory, write the script below:
#!/bin/bash
# Define the threshold for disk usage
threshold=80
# Get the disk usage for the current directory
disk_usage=$(df -h . | awk 'NR==2{print $5}')
# Extract the percentage value from the output
usage_percentage=$(echo "$disk_usage" | tr -d '%')
# Compare the disk usage against the threshold
if [ "$usage_percentage" -gt "$threshold" ]; then
echo "Disk usage for the current directory is above the threshold! Current usage: $disk_usage"
else
echo "Disk usage for the current directory is within the threshold. Current usage: $disk_usage"
fi
This script checks the disk usage for the current directory by running the df -h.
command. It extracts the disk usage percentage from the command’s output using awk
and stores it in the disk_usage variable. The awk 'NR==2{print $5}'
part prints the 5th field (disk usage percentage) from the second line of the df command output.
Then, the script removes the percentage sign from the disk_usage value using tr -d '%'
and saves it as usage_percentage. It compares usage_percentage with a predefined threshold value (set to 80%).
If the disk usage exceeds the threshold, it prints a message stating that the disk usage is above the threshold. Otherwise, it prints a message indicating that the disk usage is within the threshold.
The image shows that 92% of disk space is used by the current directory which is above the preset threshold.
2. Ping Test of a Site Using Output of Commands
The ping command is the easy way to find the average ping test time. Now see a bash script to execute the ping test of a site using the output of commands:
#!/bin/bash
# Prompt the user to enter the domain
read -p "Enter the domain to ping: " domain
ping_avg=$(ping -q -c 4 $domain | grep rtt)
echo "Avg ping time for $domain: $ping_avg"
The given script prompts the user to enter a domain name to ping. Once the user provides the input, the script uses the ping
command to calculate the average ping time. The -q
option ensures that only summary information is displayed. The output of the ping command is then passed through grep
to extract the line containing the round-trip time (rtt). This filters out the average ping time and stores the output in the ping_avg variable using command substitution. Finally, the script displays the average ping time for the entered domain by echoing the values of the domain and ping_avg variables.
Here, based on the given site domain the script finds the average ping time of the site linuxsimply.com.
3. Create Files Based on the Output of Commands
One may need to perform certain tasks based on the output of commands in a Bash script. For example, one may want to create files based on the output of different other commands. Follow the script below to visualize this:
#!/bin/bash
file="message.txt" # Replace with the actual filename you want to read
# Check if the file exists in the current directory
if [ ! -f "$file" ]; then
echo "File '$file' does not exist in the current directory."
exit 1
fi
# Count occurrences of the word "hidden" in the file
count=$(grep -o -i "hidden" "$file" | wc -l)
# Display the result
echo "Occurrences of 'hidden' in '$file': $count"
# Create new files for each hidden message
for ((i=1; i<=$count; i++)); do
touch "hidden_message${i}.txt"
done
# List the created files
echo "Created files for each hidden message:"
ls hidden_message*.txt
This script checks if a file named message.txt exists in the current directory. If the file does not exist, it displays an error message and exits. If the file exists, it counts the number of occurrences of the word “hidden” (case-insensitive) in the file using the grep command and saves the count in the variable count. Then, it creates new files named “hidden_message1.txt”, “hidden_message2.txt”, and so on, up to the count of occurrences. Finally, it lists the names of the created files using the ls
command.
The image shows that there is no message.txt file in the current directory. Let’s create one and put some text in it.Using the cat command one can print the text of message.txt. It seems the word “hidden” is 3 times in the text. Let’s see what happens after running the script.So this time the script finds the message.txt file and counts the word hidden in the text. After successfully counting that specific word it creates new files for each instance of the word “hidden”.
Error in Variable Usage That Stores Command Output
Sometimes prior familiarity with other programming languages may cause errors in variable assigning in Bash. Moreover one must have sufficient knowledge about command substitution to avoid such issues. You can go through the following two issues to have a better understanding.
A. Wrong Command Substitution
One may end up with a wrong command substitution because of a syntax error.
#!/bin/bash
$(echo $(ls -l))
In a Bash script, command substitution does not operate in this manner. One can use echo outside of the dollar sign or, instead, store the output in a variable and then echo it.
echo $(ls -l)
output=$(ls -l)
echo $output
B. Incorrect Variable Assignment
Sometimes incorrect variable assignment causes errors in processing the variable later in the script. For example,
set $(hostname --short)=$(virsh --readonly list --state-running --name)
This is an example of a wrong variable assignment in Bash. The output of virsh
command can’t be stored in the output of hostname
command. Rather one can use variables to store output and later use those for further processing or printing. For example,
host=$(hostname --short)
state=$(virsh --readonly list --state-running --name)
Conclusion
In conclusion, there are mainly two ways of substituting commands in Bash. The dollar sign method is easy to comprehend. On the other hand, the backtick method can be long-winded and often cause errors. Hope you understand the techniques to set the output of a command to a variable in Bash.
People Also Ask
How to use a variable in command?
Just give a dollar($) sign before using a variable in a command. This will retrieve the value stored in the variable and can be used as parameters or arguments of a command.
Why Bash variable command is not found?
One may set a command or multiple commands in a variable. This is often known as an alias. One may set an alias wrongly and hence can not find it. This often occurs due to unnecessary whitespaces on both sides of equal sign.
How to redirect output of Bash command?
To redirect the output of Bash command to a file or to another command one can use the arrow sign(>).
How to write multiline shell command in Bash?
To write multiline shell command in Bash, you can use backslash \
. Use backslash (\) at the end of a line to continue the command to the next line. Here’s an example:
echo "This is a/
multiline/
command"
This will give a single-line output: This is a multiline command.
How can I suppress output of a command in Linux?
To suppress the output of a command in Linux, you can redirect both standard output and standard error in the /dev/null file. This special file discards data. Here’s the syntax: command > /dev/null 2>&1
. If you want to suppress only standard output, you can use this syntax: command > /dev/null
.
Related Articles
- How to Print Output in Bash [With 6 Practical Examples]
- What is Echo Command in Bash [With 3 Practical Examples]
- How to Echo New Line in Bash [6 Practical Cases]
- Cat Command in Bash [With 4 Practical Examples]
- How to Save Bash Output to File? [3 Practical Cases]
- How to Save Bash Output to Variable? [With Practical Cases]
- How to Suppress Output in Bash [3 Cases With Examples]
- How to Change Color of Output Using Bash Script? [Easy Guide]
<< Go Back to Bash Output | Bash I/O | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners