1

I have the following:

a=$(grep pattern file_not_exist)
echo $a. #turns out a is empty

But I can see the grep complaining: grep: file_not_exist: No such file or directory. Why is the error messages from grep not assigned to be the value of shell variable a? And if we want this kind of redirection, how to do it?

I am a shell green hand and just started. It seems stdout output are assigned to the shell variable. Could you point me to the documentation describing this kindly?

Thanks!

Han XIAO
  • 1,148
  • 9
  • 20
  • You can of course ensure that stdout **and** stderr end up in the same variable, as RamanSailopal explained it. You can also, with some effort, get stdout and stderr into different variables. But why would you want to? In a script, you only need to know whether there WAS an error (for instance, to prematurely abort the script), and the error message should either be shown immediately to the user, or be thrown away. In both cases, you don't need it in a variable. – user1934428 Feb 19 '21 at 11:06
  • BTW, variable assignment is described in the bash man page in the section _PARAMETERS_. Redirection is described in the section _REDIRECTION_. – user1934428 Feb 19 '21 at 11:19

1 Answers1

1

a will contain the output of the command returned to stdout. The error will be returned to sterr and so to get the error in the variable, you will need to redirect sterr to stout and so:

a=$(grep pattern file_not_exist 2>&1)

Here, 2 represent stdrr and 1 stdout.

Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18