加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 21:10:01 所属栏目:安全 来源:网络整理
导读:参见英文答案 How to get error output and store it in a variable or file????????????????????????????????????3个 我试图将复制命令的错误消息存储到变量中.但它没有发生 Unix命令 log=`cp log.txt`cp: missing destination file operand after `log.txt
参见英文答案 > How to get error output and store it in a variable or file????????????????????????????????????3个
我试图将复制命令的错误消息存储到变量中.但它没有发生

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读