How to Save Command Output as Variable in Bash?

Introduction

In bash scripts, assigning the output of a command to variables can be convenient by storing the outputs of the commands and using them later.

In this short guide, we will take a look at how you can store the output of a command as a variable in Bash.

The Basics To Set Up Variables

Saving the output of a command as a variable is achieved through command substitution. Command substitution is a wrapper that executes the command in a subshell environment, and replaces the wrapped command with the standard output of the environment in which the command was run. This output can then be referenced later, if connected to a reference variable!

Command substitution can be achieved through back ticks or the dollar sign with parentheses:

`command`

$(command)

There's debate as to whether `command` (backticks) or $(command) (dollar sign and parentheses) should be used as the "best practice". $(command) works well in nesting, and improves readability in some cases, but you can go with either syntax in the preceding examples.

That being said - assigning the output of a command to a variable in Bash is as easy as:

VARIABLE=$(command)
echo "${VARIABLE}"

Running ${variable} is known as parameter expansion, and is used to evaluate and fetch the value associated with a reference variable.

Let's now take a look at the simple example of setup a variable for a command to change the output color:

#!/bin/bash
GREEN=$(tput setaf 2)
echo "${GREEN}Please"

ORANGE=$(tput setaf 9)
echo "${ORANGE}Visit"

echo "${GREEN}Paris"

In the snippet, we've used the tput command and assigned the returned value of those commands to print colorful text. The setaf changes the foreground color, and 3 (green) and 9 (orange) are color codes.

Now we'll move on to another example that contains multiple conditions to set up variables for different commands:

#!/bin/bash
PERSON=$(whoami)
echo -e "Hey ${PERSON}! I am Charlie\n"

DETAILS=$(uname -a)
echo -e "You're running this script on:\n${DETAILS}\n"

DATES=$(date)
echo -e "The script is being run on:\n${DATES}\n"

CREATE=$(touch $(date +"%d%m%Y").txt)
echo -e "A text file logging this run is created.${CREATE}\n"

LOCATION=$(ls \
  -l *txt)
echo -e "Saved text file at: ${LOCATION}"

In the above script, the whoami command returns the current user's username. The uname -a returns the system information, and the date returns the current time and date.

Note: We can chain variable assignment by adding multiple commands in a single nested call. The CREATE variable contains the output of the touch command, which in turn creates a file and sets the filename to the output of the date +"%d%m%Y command.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Finally, we add a multiline command variable assignment concept by adding a backslash (\) between the ls command -l flag to display only text files using *.txt. The backslash is an escape character that informs the shell not to interpret the next character.

In the echo command, we added the -e flag to use the special character, i.e., \n (newline), to print the output in the new line.

We get the following result after executing the script:

$ ./variable.sh

Conclusion

In this short guide, we've taken a look at how you can set the output of a command to a variable in Bash. We've taken a look at the difference between the syntaxes for command substitution, noting the readability improvements of $(command) over backtick based substitution. Then, we've taken a look at several examples of both simple assignment and chained/nested output assignment.

Last Updated: November 17th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms