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.
Key Takeaways
- Learning about Command Substitution.
- Learning about Variable Assigning.
- Uses of command outputs.
Free Downloads
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.
Method 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.
❶ At first, launch an Ubuntu Terminal.
❷ Write the following command to open a command_output.sh file in the build-in nano editor:
nano command_output.sh
- nano: Opens a file in the Nano text editor.
- command_output.sh: Name of the file.
#!/bin/bash
dir=$(pwd)
echo "Your current directory: $dir"
❹ Use the following command to make the file executable:
chmod u+x command_output.sh
- chmod: Changes permissions.
- u+x: Giving the owner executing permission.
- command_output.sh: Name of the script.
./command_output.sh
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, open a file named ‘option.sh’ & write the following script in the nano editor.
Scripts (option.sh) >
#!/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
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.
Finally, run the file using the following command:
./option.sh
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.
Scripts (out_multiplecommand.sh) >
#!/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."
Finally, run the file using the following command:
./out_multiplecommand.sh
When running the code, it shows the total files of the current directory and how many of them are empty.
Method 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, open a file named ‘backtick_subs.sh’ & write the following script in the nano editor.
Scripts (backtick_subs.sh) >
#!/bin/bash
current_user=`whoami`
echo “The logged in user is: $current_user”
Finally, run the file using the following command to see the output:
./backtick_subs.sh
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 named ‘multiline_subs.sh’ & write the following script in the nano editor.
Scripts (multiline_subs.sh) >
#!/bin/bash
info=`(grep -l\
-i -n -w\
"hidden" *.txt)`
echo $info
Finally, run the file using the following command to see the output:
./out_multiline_subs.sh
The output shows that there is a file named message.txt that contains the word hidden.
#!/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 named ‘path.sh’ & write the following script in the nano editor.
Scripts (path.sh) >
#!/bin/bash
dirname=`/bin/pwd`
echo “Current directory:$dirname”
Finally, run the file using the following command to see the output:
./path.sh
Comparative Analysis of Methods
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.
Case 1: Disk Usage of Current Directory
To visualize the disk usage of the current directory open a file named ‘disk_usage.sh’ & write the following script in the nano editor.
Scripts (disk_usage.sh) >
#!/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
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.
To run the script execute the following command in the terminal:
./disk_usage.sh
The image shows that 92% of disk space is used by the currrent diretory which is above the preset threshold.
Case 2: Ping Test of a Site Using Output of Commands
The ping command is the easy way to find the average ping test time. Open a file named ‘ping_test.sh’ & write the following script in the nano editor.
Scripts (ping_test.sh) >
#!/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"
To run the script execute the following command in the terminal:
./ping_test.sh
Here, based on the given site domain the script finds the average ping time of the site linuxsimply.com.
Case 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. First, open a file named ‘hidden.sh’ & write the following script in the nano editor.
Scripts (hidden.sh) >
#!/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
Finally, you can run the script using the following command:
./hidden.sh
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.
Scripts (issue.sh) >
#!/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
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