Just redirect the stdout (normal output) to /dev/null
and keep the stderror:
a=$(cp log.txt 2>&1 >/dev/null)
See an example:
$ a=$(cp log.txt 2>&1 >/dev/null)
$ echo "$a"
cp: missing destination file operand after ‘log.txt’
Try 'cp --help' for more information.
The importance to >/dev/null
to keep away to normal output that in this case we do not want:
$ 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
Note the need of quoting $a
when calling it, so that the format is kept. Also, it is better to use $()
rather than , as it is easier to nest and also
is deprecated.
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
.