0
res=`echo "hello" > /home/directory/folder1/xxx.txt 2>&1`

/home/directory/folder1/xxx.txt: Permission denied

echo $res

EMPTY LINE

i expect the error to be stored in the variable res , why it is not getting stored and what to do for having error stored in the variable ?

Ravi Soni
  • 953
  • 1
  • 7
  • 17
  • 2
    You redirected the error message to `/home/directory/folder1/xxx.txt`, which isn't writable for you. – Ipor Sircer Jan 24 '17 at 14:00
  • 2
    In this case the error comes from the shell, not from the command. At the same time your redirect _everything_ (both `stdout` and `stderr` of the command) to a file. Therefore, there are at least two problems with your example, and it is not clear which one you are asking about. – kirelagin Jan 24 '17 at 14:00

2 Answers2

3

Your error comes from the shell, not from the command, therefore you have to redirect the output stream of the shell, for example, like this:

$ res=$(bash -c 'echo "hello" > /home/directory/folder1/xxx.txt' 2>&1)
$ echo $res
bash: /home/directory/folder1/xxx.txt: No such file or directory

Actually, there exists a somewhat nicer syntax for creating subshells:

$ res=$((echo "hello" > /home/directory/folder1/xxx.txt) 2>&1)
$ echo $res
bash: /home/directory/folder1/xxx.txt: No such file or directory
kirelagin
  • 13,248
  • 2
  • 42
  • 57
1

use bracket

res=`(echo "hello" > /home/directory/folder1/xxx.txt) 2>&1`

Explanation : you redirect data to any stream only once.

res=`echo "hello" > /home/directory/folder1/xxx.txt 2>&1`

over here you are redirecting first "hello" to output stream and then the error to output stream which is not correct. So to tell the shell that we want to redirect the error produced from anything out of the command :

echo "hello" > /home/directory/folder1/xxx.txt

we should use parentheses to wrap the command.

Ravi Soni
  • 953
  • 1
  • 7
  • 17