bash - 将命令输出的错误消息存储到 shell 变量中

标签 bash shell unix

<分区>

我正在尝试将复制命令的错误消息存储到变量中。但它没有发生

Unix 命令

log=`cp log.txt`
cp: missing destination file operand after `log.txt'
Try `cp --help' for more information.

echo $log

<nothing displayed>

我想将上面的错误消息存储到一个变量中,这样我就可以随时回显它

最佳答案

只需将 stdout(正常输出)重定向到 /dev/null 并保留 stderror:

a=$(cp log.txt 2>&1 >/dev/null)

看一个例子:

$ a=$(cp log.txt 2>&1 >/dev/null)
$ echo "$a"
cp: missing destination file operand after ‘log.txt’
Try 'cp --help' for more information.

>/dev/null 避免正常输出的重要性,在这种情况下我们不希望这样:

$ ls a b
ls: cannot access a: No such file or directory
b
$ a=$(ls a b 2>&1)
$ echo "$a"
ls: cannot access a: No such file or directory
b
$ a=$(ls a b 2>&1 >/dev/null)
$ echo "$a"
ls: cannot access a: No such file or directory

注意调用时需要引用$a,这样格式就保持不变了。此外,最好使用 $() 而不是 ,因为它更容易嵌套,而且 已被弃用。


What does 2>&1 mean?

1 is stdout. 2 is stderr.

Here is one way to remember this construct (altough it is not entirely accurate): at first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as "redirect stderr to a file named 1". & indicates that what follows is a file descriptor and not a filename. So the construct becomes: 2>&1.

关于bash - 将命令输出的错误消息存储到 shell 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21481293/

相关文章:

bash - 将配置单元查询输出存储在 shell 脚本变量中

bash - 测试是否有任何文件超过 7 天

perl - 如何获取另一个命令行工具 "wrap"的未修改命令行参数?

c - 解释 Unix 中程序的文字运行时间

c - 为什么 'EINTR' 未声明?

linux - 如何根据PORT ID搜索获取PID和PNAME值。输出应该是通用的

php - 从 shell 脚本中的 php 脚本检索退出状态

bash - 在 emacs shell 中运行 unix date util 的问题

linux - 如何从 shell 脚本内部更新 shell 脚本

C - 系统调用 - N 个子进程的数组分区 -