How to Set Command Output to Variable in Bash [2 Methods]

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 to set the output of command to variables: using the dollar sign ($) method and the backticks (`) method.

You can read the Comparative Analysis of Methods to find the easy one for you.

1. Set Command Output to Variable Using Dollar Sign

This method tells how to substitute a Bash command using the dollar sign ($) and store the output in a variable for further use in a script.

A. Setting the Output of a Single Command to Variable

To store the output of the pwd command and use it later in the script, check out the following bash script:

#!/bin/bash

dir=$(pwd)
echo "Your current directory: $dir"
EXPLANATION

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.

bash set output of command to variableThe output image shows the current directory as expected.

B. Setting Command With Formatting

A Bash Command might have different options and arguments. The output of the command significantly varies based on the usage of those options.

To format command output with options and store the output in a variable, 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
EXPLANATION

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.

set variable to output of a command with option in BashWhen running the script it shows today’s date with the dd/mm format.

C. Setting the Output of Multiple Commands With Options and Arguments

In Bash script, multiple commands can be used for various purposes in a single line. Now, to see how to set the output of multiple commands in a variable and use it later for more complex tasks, go through the script below:

#!/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."
EXPLANATION

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.

 Set output of multiple command to a variable in BashWhen running the code, it shows the total files of the current directory and how many of them are empty.

2. Set Command Output to 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 the 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"
EXPLANATION

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.

Backtick substitution in BashThe 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
EXPLANATION

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, the backslash (\) is used for each new line of command substitution.

Setting output of multiline command into a variable in BashThe 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)``

Issue of nested command substitution using backtick

The script shows a syntax 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"
EXPLANATION

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.

Set output of a command to a variable using path of the command

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
  • More readable and visually separates the command.
  • Supports easy nesting of commands.
  • May not be available in all UNIX system.
Backtick substitution
  • Widely supported in UNIX systems.
  • Less readable, may clutter the script.
  • Supports nesting but can become visually confusing.

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.

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


<< Go Back to Bash Output | Bash I/O | Bash Scripting Tutorial

4.8/5 - (5 votes)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment