leanhhao
leanhhao

Reputation: 15

How to redirect standard error to a file

In linux if I want to redirect standard error to a file, I can do this:

$ls -l /bin/usr 2> ls-error.txt

But when I try:

$foo=
$echo ${foo:?"parameter is empty"} 2> ls-error.txt

The result in terminal is:

bash: foo: parameter is empty

It doesn't work! Can somebody explain why? I thought ${parameter:?word} would send the value of word to standard error.

Upvotes: 1

Views: 417

Answers (3)

Bsquare ℬℬ
Bsquare ℬℬ

Reputation: 4487

In case you would like to redirect both sandard and error output, AND to still get these messages when executing your command, you can use the tee command:

$echo ${foo:?"parameter is empty"} |& tee -a ls-error.txt

Upvotes: -1

Petr Skocik
Petr Skocik

Reputation: 60143

echo ${foo:?"parameter is empty"} 2>ls-error.txt redirects the stderr of echo, but the error message is produced by the shell while expanding ${foo:?"parameter is empty"}.

You can get the result you want by redirecting a block (or a subshell) instead so that the shell's stderr is included in the redirection:

{ echo "${foo:?"parameter is empty"}"; } 2>ls-error.txt

Upvotes: 3

Marcin Krasowski
Marcin Krasowski

Reputation: 686

Try this command: ($echo ${foo:?"parameter is empty"}) 2> ls-error.txt

Upvotes: 0

Related Questions