2

I know that we can assign the output of a command in a script as below:

res=$(ls)    # assign the output of ls to res

Now I want to assign the error message to a variable:

res=$(XXXXXXX)

When I execute the script, which contains the code above, I get an error message on the terminal: command not found, whereas res is still empty.

Is it possible to assign command not found to res while there is nothing shown on the terminal?

Inian
  • 80,270
  • 14
  • 142
  • 161
Yves
  • 11,597
  • 17
  • 83
  • 180
  • Though this looks like a dupe, couldn't find one myself. – Inian Jan 11 '18 at 12:09
  • 1
    Possible duplicate of [How to store standard error in a variable in a Bash script](https://stackoverflow.com/questions/962255/how-to-store-standard-error-in-a-variable-in-a-bash-script) – PesaThe Jan 11 '18 at 12:09
  • @PesaThe: I saw that but OP says `so redirecting stderr into stdout is not helpful, in this case.` – Inian Jan 11 '18 at 12:11
  • @Inian oops, I saw this [answer](https://stackoverflow.com/a/962268/6176817) and instantly thought OP tried to do exactly the same thing. – PesaThe Jan 11 '18 at 12:13

1 Answers1

2

Yes it can be done, just make sure to send stderr(2) stream to stdout(1) and suppress stdout to NULL(/dev/null)

res=$( non_existent_command 2>&1 >/dev/null )
Inian
  • 80,270
  • 14
  • 142
  • 161