如何在Bash中将变量设置为命令的输出? [英] How do I 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
当我从命令行运行此脚本并将参数传递给它时,我没有得到任何输出.但是,当我运行$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.
如何获取需要在脚本中运行的命令的结果,将其保存到变量中,然后在屏幕上输出该变量?
How can one 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?
推荐答案
除了反引号`command`
,来完成Command-Substitution"rel =" noreferrer>命令替换,我发现它们更易于阅读,并且可以嵌套.
In addition to backticks `command`
, command substitution can be done with $(command)
or "$(command)"
, which I find easier to read, and allows for nesting.
OUTPUT=$(ls -1)
echo "${OUTPUT}"
MULTILINE=$(ls \
-1)
echo "${MULTILINE}"
引用("
)对于保留多行变量值很重要;它在任务的右侧是可选的,例如
Quoting ("
) does matter to preserve multi-line variable values; it is optional on the right-hand side of an assignment, as word splitting is not performed, so OUTPUT=$(ls -1)
would work fine.
这篇关于如何在Bash中将变量设置为命令的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!