如何在Shell脚本中获取命令的输出信息

3

我希望能在shell脚本中执行一个命令。

这个命令将会有一个返回码,如果成功则为0,否则为非0。

如果成功,它会打印一些东西。

现在我需要在shell脚本中获取这些打印出来的内容。有没有直接将其重定向到变量的方法?

我知道我可以将其重定向到文件,然后读取该文件。但是否有更好的方法?

感谢您的信息。


哪个shell? sh?csh?ksh?其他? - Bert F
2个回答

4
您可以使用$(...)操作符将命令的输出捕获为字符串。您可能还看到过旧的反引号`...`语法,它也可以实现相同的功能。
output=$(command)
output=`command`

echo "$output"

Command Substitution

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.


2
var=`command`

反引号会执行命令并返回结果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接