Linux command result variable

How can I store a command in a variable in a shell script?

I would like to store a command to use at a later time in a variable (not the output of the command, but the command itself). I have a simple script as follows:

command="ls"; echo "Command: $command"; #Output is: Command: ls b=`$command`; echo $b; #Output is: public_html REV test. (command worked successfully) 
Command: ls | grep -c '^' ls: cannot access |: No such file or directory ls: cannot access grep: No such file or directory ls: cannot access '^': No such file or directory 

12 Answers 12

x="ls | wc" eval "$x" y=$(eval "$x") echo "$y" 

eval is an acceptable practice only if you trust your variables’ contents. If you’re running, say, x=»ls $name | wc» (or even x=»ls ‘$name’ | wc» ), then this code is a fast track to injection or privilege escalation vulnerabilities if that variable can be set by someone with less privileges. (Iterating over all subdirectories in /tmp , for instance? You’d better trust every single user on the system to not make one called $’/tmp/evil-$(rm -rf $HOME)\’$(rm -rf $HOME)\’/’ ).

eval is a huge bug magnet that should never be recommended without a warning about the risk of unexpected parsing behavior (even without malicious strings, as in @CharlesDuffy’s example). For example, try x=’echo $(( 6 * 7 ))’ and then eval $x . You might expect that to print «42», but it probably won’t. Can you explain why it doesn’t work? Can you explain why I said «probably»? If the answers to those questions aren’t obvious to you, you should never touch eval .

@Student, try running set -x beforehand to log the commands run, which will make it easier to see what’s happening.

@Student I’d also recommend shellcheck.net for pointing out common mistakes (and bad habits you shouldn’t pick up).

Do not use eval ! It has a major risk of introducing arbitrary code execution.

BashFAQ-50 — I’m trying to put a command in a variable, but the complex cases always fail.

Put it in an array and expand all the words with double-quotes «$» to not let the IFS split the words due to Word Splitting.

and see the contents of the array inside. The declare -p allows you see the contents of the array inside with each command parameter in separate indices. If one such argument contains spaces, quoting inside while adding to the array will prevent it from getting split due to Word-Splitting.

declare -p cmdArgs declare -a cmdArgs='([0]="date" [1]="+%H:%M:%S")' 

and execute the commands as

Читайте также:  Astra linux intel hd graphics driver

(or) altogether use a bash function to run the command,

and call the function as just

POSIX sh has no arrays, so the closest you can come is to build up a list of elements in the positional parameters. Here’s a POSIX sh way to run a mail program

# POSIX sh # Usage: sendto subject address [address . ] sendto()

Note that this approach can only handle simple commands with no redirections. It can’t handle redirections, pipelines, for/while loops, if statements, etc

Another common use case is when running curl with multiple header fields and payload. You can always define args like below and invoke curl on the expanded array content

curlArgs=('-H' "keyheader: value" '-H' "2ndkeyheader: 2ndvalue") curl "$" 
payload='<>' hostURL='http://google.com' authToken='someToken' authHeader='Authorization:Bearer "'"$authToken"'"' 

now that variables are defined, use an array to store your command args

curlCMD=(-X POST "$hostURL" --data "$payload" -H "Content-Type:application/json" -H "$authHeader") 

and now do a proper quoted expansion

Источник

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

Читайте также:  Linux chmod запуск скрипта

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.

Читайте также:  Kali linux поиск человека

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 do I assign the output of a command to a variable?

Is there a way to assign a value to a variable, that value which we get in terminal by writing any command? Example command: sensors From that we get CPU temperature. How can I assign this value to a temp_cpu variable?

This question is more suited to Super User or to Unix & Linux. Try temp_cpu=$(sensors) (this will turn newlines to spaces, though). You can use grep to filter the specific info you need, too.

@Tshepang, this question is not specific to Ubuntu, it’s just about the Unix-like shell. Thus, Unix & Linux.

Did the policy/general opinion change? I thought this site welcomed questions that are not necessarily specific to Ubuntu.

2 Answers 2

Yes, you use my_var=$(some_command) . For example:

$ foo=$(date) $ echo $foo Mon Jul 22 18:10:24 CLT 2013 

Or for your specific example, using sed and grep to get at the specific data you want:

$ cpu_temp=$(sensors acpitz-virtual-0 | grep '^temp1:' | sed 's/^temp1: *//;s/ .*//') $ echo $cpu_temp +39.0°C 

You can also store the value of command as follows:

variableName=`command` $variableName 
currentDirectory=`pwd` $currentDirectory 

This works but this type of substitution cannot be nested, so the other option is preferred. @bac0n I’ve fixed the formatting problem.

You must log in to answer this question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.13.43530

Ubuntu and the circle of friends logo are trade marks of Canonical Limited and are used under licence.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью
Adblock
detector