Shell scripts allow you to automate processes & tasks in Linux. We often run many commands in our shell scripts. Sometimes you may need to assign command output to variable in bash, capture output of command or set variable to command output. This is a common requirement and can pose difficulty to beginners. In this article, we will learn how to assign command output to variable in shell script.
How to Assign Command Output to Variable in Shell Script
Here are the different ways to store the output of a command in shell script. You can also use these commands on terminal to store command outputs in shell variables.
variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name=`command` variable_name=`command [option ...] arg1 arg2 ...`
In the above command you need to enclose the command, with its options, within $(…) or within backquotes `…`
Here is an example to store output of who command in Linux.
$ CURRENT_USERS=$(who)
Once you have stored the output of command in shell variable, you can access it by adding $ prefix at its beginning, as shown below.
$ echo $CURRENT_USERS
Here is the command to store the same command using backquotes.
$ CURRENT_USERS=`who` $ echo $CURRENT_USERS
Here is a simple shell script to illustrate the above commands. Create an empty shell script.
$ sudo vi sample.sh
Add the following lines to it.
#!/bin/sh CURRENT_USERS=$(who) echo $CURRENT_USERS
Save and close the file. Change its permissions to make it an executable.
$ sudo chmod +x sample.sh
Run the shell script with the following command.
$ ./sample.sh 3
In this article, we have learnt how to store command output to shell variable. You can use them in terminal or shell scripts, as per your requirement.
Also read:
How to Disable Package Updates in Yum/Dnf
How to Group By Multiple Columns in Python Pandas
How to Access Environment Variables in Python
How to Password Protect PDF in Python
How to Read Inputs As Numbers in Python
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.