只需将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.