scripting - 如何在Shell脚本中获取命令的打印信息

标签 scripting shell

我想在 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/

相关文章:

linux - 需要添加 50 个具有特定 uid 范围的用户、已识别的 userid 列表、自定义用户评论和自定义主要组

bash:将整个命令(带参数)传递给函数

shell - 如何让expect -c在单行而不是脚本中工作

linux - 编辑不带临时文件的配置文件

linux - oracle启动成功后如何执行shell脚本

python - 奇怪的 python 打印行为

linux - 语法错误 : redirection unexpected netcat busybox

linux - 定义每次使用时要评估的 bash 变量

shell - 提取两个字符串之间的文本。这些字符串有空格,保存在变量中

linux - ". ./filename "命令是如何工作的