Yves
Yves

Reputation: 12431

How to assign standard error stream output to a variable in bash?

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?

Upvotes: 2

Views: 165

Answers (1)

Inian
Inian

Reputation: 85865

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 )

Upvotes: 2

Related Questions