How to set a variable to the output of a command in Bash?
I have a pretty simple script that is something like the following:
#!/bin/bash
VAR1="$1"
MOREF='sudo run command against $VAR1 | grep name | cut -c7-'
echo $MOREF
When I run this script from the command line and pass it the arguments, I am not getting any output. However, when I run the commands contained within the $MOREF
variable, I am able to get output.
I would like to know how one can take the results of a command that needs to be run within a script, save it to a variable, and then output that variable on the screen?
In addition to the backticks, you can use $()
, which I find easier to read, and allows for nesting.
OUTPUT="$(ls -1)"
echo "${OUTPUT}"
Quoting ( "
) does matter to preserve multi-line values.
Update (2018): the right way is
$(sudo run command)
You're using the wrong kind of apostrophe. You need `
, not '
. This character is called "backticks" (or "grave accent").
Like this:
#!/bin/bash
VAR1="$1"
VAR2="$2"
MOREF=`sudo run command against "$VAR1" | grep name | cut -c7-`
echo "$MOREF"
As they have already indicated to you, you should use 'backticks'.
The alternative proposed $(command)
works as well, and it also easier to read, but note that it is valid only with bash or korn shells (and shells derived from those), so if your scripts have to be really portable on various Unix systems, you should prefer the old backticks notation.
上一篇: 用&符号启动PHP函数是什么意思?
下一篇: 如何将变量设置为Bash中命令的输出?