4

I am trying to store error meesage of a copy command in to a variable. But its not happening

Unix Command

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 store above error message into a variable so that i can echo it whenever i want

logan
  • 7,946
  • 36
  • 114
  • 185

1 Answers1

5

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.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Please explain so that i can mark as answer :) – logan Jan 31 '14 at 13:58
  • 1
    As devnull was commenting in his deleted answer, you can check http://en.wikipedia.org/wiki/Redirection_%28computing%29 Also see my updated answer. – fedorqui Jan 31 '14 at 14:00
  • For commands that write to both standard output and standard error, you'll want to throw away standard output after redirecting standard error: `$( command 2>&1 >/dev/null )`. – chepner Jan 31 '14 at 14:49
  • You are completely right, @chepner, just updated showing an example of what you comment. Thanks! – fedorqui Jan 31 '14 at 14:54