- How can I assign the output of a command to a shell variable?
- 3 Answers 3
- BASH command output to the variable
- Command Substitution Syntax:
- Single command output to a variable
- Example#1:
- Example#2:
- Example#3:
- Example#4:
- Using command substitution in loop
- Example#5:
- Using nested commands
- Example#6:
- Using Command path
- Example#7:
- Using Command Line argument
- Example#8:
- Conclusion:
- About the author
- Fahmida Yesmin
- How To Assign Output of a Linux Command to a Variable
How can I assign the output of a command to a shell variable?
I want to assign the result of an expression (i.e., the output from a command) to a variable and then manipulate it – for example, concatenate it with a string, then echo it. Here’s what I’ve got:
#!/bin/bash cd ~/Desktop; thefile= ls -t -U | grep -m 1 "Screen Shot"; echo "Most recent screenshot is: "$thefile;
Screen Shot 2011-07-03 at 1.55.43 PM.png Most recent screenshot is:
So, it looks like that isn’t getting assigned to $thefile , and is being printed as it’s executed. What am I missing?
3 Answers 3
A shell assignment is a single word, with no space after the equal sign. So what you wrote assigns an empty value to thefile ; furthermore, since the assignment is grouped with a command, it makes thefile an environment variable and the assignment is local to that particular command, i.e. only the call to ls sees the assigned value.
You want to capture the output of a command, so you need to use command substitution:
thefile=$(ls -t -U | grep -m 1 "Screen Shot")
(Some literature shows an alternate syntax thefile=`ls …` ; the backquote syntax is equivalent to the dollar-parentheses syntax except that quoting inside backquotes is weird sometimes, so just use $(…) .)
Other remarks about your script:
- Combining -t (sort by time) with -U (don’t sort with GNU ls ) doesn’t make sense; just use -t .
- Rather than using grep to match screenshots, it’s clearer to pass a wildcard to ls and use head to capture the first file:
thefile=$(ls -td -- *"Screen Shot"* | head -n 1)
echo "Most recent screenshot is: $thefile"
If you have GNU find and sort (in particular if you’re running non-embedded Linux or Cygwin), there’s another approach to finding the most recent file: have find list the files and their dates, and use sort and read (here assuming bash or zsh for -d » to read a NUL-delimited record) to extract the youngest file.
IFS=/ read -rd '' ignored thefile < <( find -maxdepth 1 -type f -name "*Screen Shot*" -printf "%T@/%p\0" | sort -rnz)
If you're willing to write this script in zsh instead of bash, there's a much easier way to catch the newest file, because zsh has glob qualifiers that permit wildcard matches not only on names but also on file metadata. The (om[1]) part after the pattern is the glob qualifiers; om sorts matches by increasing age (i.e. by modification time, newest first) and [1] extracts the first match only. The whole match needs to be in parentheses because it's technically an array, since globbing returns a list of files, even if the [1] means that in this particular case the list contains (at most) one file.
#!/bin/zsh set -e cd ~/Desktop thefile=(*"Screen Shot"*(om[1])) print -r "Most recent screenshot is: $thefile"
BASH command output to the variable
Different types of bash commands need to be run from the terminal based on the user’s requirements. When the user runs any command from the terminal then it shows the output if no error exists otherwise it shows the error message. Sometimes, the output of the command needs to be stored in a variable for future use. Shell command substitution feature of bash can be used for this purpose. How you can store different types of shell commands into the variable using this feature is shown in this tutorial.
Command Substitution Syntax:
variable =$ ( command )
variable =$ ( command [ option… ] argument1 arguments2 … )
variable =$ ( / path / to / command )
variable = ` command `
variable = ` command [ option… ] argument1 arguments2 … `
variable = `/ path / to / command `
***Note: Don’t use any space before and after the equal sign when using the above commands.
Single command output to a variable
Bash commands can be used without any option and argument for those commands where these parts are optional. The following two examples show the uses of simple command substitution.
Example#1:
bash `date` command is used to show the current date and time. The following script will store the output of `date` command into $current_date variable by using command substitution.
Example#2:
`pwd` command shows the path of the current working directory. The following script stores the output of `pwd` command into the variable, $current_dir and the value of this variable is printed by using `echo` command.
Command with option and argument
The option and argument are mandatory for some bash commands. The following examples show how you can store the output of the command with option and argument into a variable.
Example#3:
Bash `wc` command is used to count the total number of lines, words, and characters of any file. This command uses -c, -w and -l as option and filename as the argument to generate the output. Create a text file named fruits.txt with the following data to test the next script.
fruits.txt
Run the following commands to count and store the total number of words in the fruits.txt file into a variable, $count_words and print the value by using `echo` command.
Example#4:
`cut` is another bash command that uses option and argument to generate the output. Create a text file named weekday.txt with seven-weekday names to run the next script.
Create a bash file named cmdsub1.sh with the following script. In this script, while loop is used to read the content of weekday.txt file line by line and read the first three characters of each line by using `cut` command. After cutting, the string value is stored in the variable $day. Next, If the statement is used to check the value of $day is ‘Sun’ or not. The output will print ‘Sunday is the holiday‘ when if the condition is true otherwise it will print the value of $day.
#!/bin/bash
filename = 'weekday.txt'
while read line; do
day = ` echo $line | cut -c 1 - 3 `
if [ $day == "Sun" ]
then
echo "Sunday is the holiday"
else
echo $day
fi
done < $filename
Using command substitution in loop
You can store the output of command substitution into any loop variable which is shown in the next example.
Example#5:
Create a file named cmdsub2.sh with the following code. Here, `ls -d */` command is used to retrieve all directory list from the current directory. For loop is used here to read each directory from the output and store it in the variable $dirname which is printed later.
Using nested commands
How you can use multiple commands using pipe(|) is shown in the previous example. But you can use nested commands in command substitution where the output of the first command depends on the output of the second command and it works opposite of the pipe(|) command.
Nested command syntax:
Example#6:
Two commands, `echo` and `who` are used in this example as the nested command. Here, `who` command will execute first that print the user’s information of the currently logged in user. The output of the `who` command will execute by `echo` command and the output of `echo` will store into the variable $var. Here, the output of `echo` command depends on the output of `who` command.
Using Command path
If you know the path of the command then you can run the command by specifying the command path when using command substitution. The following example shows the use of command path.
Example#7:
`whoami` command shows the username of the currently logged in user. By default, this command is stored in /usr/bin/ folder. Run the following script to run `whoami` command using path and store in the variable, $output, and print the value of $output.
Using Command Line argument
You can use the command line argument with the command as the argument in the command substitution.
Example#8:
Create a bash file named cmdsub3.sh with the following script. `basename` command is used here to retrieve the filename from the 2 nd command line argument and stored in the variable, $filename. We know the 1 st command line argument is the name of the executing script which is denoted by $0.
Run the script with the following argument value.
Here, the basename of the path, Desktop/temp/hello.txt is ‘hello.txt’. So, the value of the $filename will be hello.txt.
Conclusion:
Various uses of command substitutions are shown in this tutorial. If you need to work with multiple commands or depended commands and store the result temporary to do some other tasks later then you can use this feature in your script to get the output.
About the author
Fahmida Yesmin
I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.
How To Assign Output of a Linux Command to a Variable
When you run a command, it produces some kind of output: either the result of a program is suppose to produce or status/error messages of the program execution details. Sometimes, you may want to store the output of a command in a variable to be used in a later operation.
In this post, we will review the different ways of assigning the output of a shell command to a variable, specifically useful for shell scripting purpose.
To store the output of a command in a variable, you can use the shell command substitution feature in the forms below:
variable_name=$(command) variable_name=$(command [option . ] arg1 arg2 . ) OR variable_name='command' variable_name='command [option . ] arg1 arg2 . '
Below are a few examples of using command substitution.
In this first example, we will store the value of who (which shows who is logged on the system) command in the variable CURRENT_USERS user:
Then we can use the variable in a sentence displayed using the echo command like so:
$ echo -e "The following users are logged on the system:\n\n $CURRENT_USERS"
In the command above: the flag -e means interpret any escape sequences ( such as \n for newline) used. To avoid wasting time as well as memory, simply perform the command substitution within the echo command as follows:
$ echo -e "The following users are logged on the system:\n\n $(who)"
Next, to demonstrate the concept using the second form; we can store the total number of files in the current working directory in a variable called FILES and echo it later as follows:
$ FILES=`sudo find . -type f -print | wc -l` $ echo "There are $FILES in the current working directory."
That’s it for now, in this article, we explained the methods of assigning the output of a shell command to a variable. You can add your thoughts to this post via the feedback section below.