Saving a command output error message to a shell variable

I am trying to save a copy command error error in a variable. But its not happening

Unix Team

log=`cp log.txt`
cp: missing destination file operand after `log.txt'
Try `cp --help' for more information.

echo $log

<nothing displayed>

I want to write the above error message to a variable so that I can echo it whenever I want

+4
source share
1 answer

Just redirect stdout (normal output) to /dev/nulland save 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/nullprevent a normal conclusion, which in this case we do not need:

$ 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 for quoting $awhen invoked so that the format is preserved. It is also better to use $()rather than , as it is easier to nest and alsoout of date.


2>&1?

1 . 2 - stderr.

( ): 2>1 stderr . " stderr 1". & , , . , : 2>&1.

+5

Source: https://habr.com/ru/post/1524705/


All Articles