<分区>
我正在尝试将复制命令的错误消息存储到变量中。但它没有发生
Unix 命令
log=`cp log.txt`
cp: missing destination file operand after `log.txt'
Try `cp --help' for more information.
echo $log
<nothing displayed>
我想将上面的错误消息存储到一个变量中,这样我就可以随时回显它
<分区>
我正在尝试将复制命令的错误消息存储到变量中。但它没有发生
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
,这样格式就保持不变了。此外,最好使用 $()
而不是 ,因为它更容易嵌套,而且
已被弃用。
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 named1
".&
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/