1

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.

leanhhao
  • 15
  • 3

3 Answers3

3

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
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
0

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

Al Sweigart
  • 11,566
  • 10
  • 64
  • 92
Marcin Krasowski
  • 668
  • 6
  • 12
-1

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
Bsquare ℬℬ
  • 4,423
  • 11
  • 24
  • 44