我想在 shell 脚本中执行命令。
此命令将有一个返回代码,无论成功与否,返回代码为 0 或非 0。
如果成功,它会打印一些东西。
现在我需要 shell 脚本中打印的内容。我怎样才能做到这一点?
我知道我可能会重定向到一个文件,然后读取该文件。有没有办法直接将其重定向到变量?
非常感谢您提供的信息。
最佳答案
您可以使用$(...)
运算符将命令的输出捕获为字符串。您可能还看到过旧的反引号 `...`
语法做同样的事情。
output=$(command)
output=`command`
echo "$output"
命令替换
Command substitution allows the output of a command to replace the command name. There are two forms:
$(command)
or
`command`
Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution
$(cat file)
can be replaced by the equivalent but faster$(< file)
.When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by
$
,`
, or\
. The first backquote not preceded by a backslash terminates the command substitution. When using the$(command)
form, all characters between the parentheses make up the command; none are treated specially.Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes.
If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results.
关于scripting - 如何在Shell脚本中获取命令的打印信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3638558/