linux脚本ls输出到变量中,bash – 将命令输出的错误消息存储到shell变量中

只需将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 named 1“. & indicates that what follows is a file

descriptor and not a filename. So the construct becomes: 2>&1.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值