Issue
a=whatever
f(){return 1}
echo $a # this gives whatever
a=$(f)
echo $a # now a is empty
Is this because command returned non zero, so command substitution failed, thus a
is set to empty? Is this a well defined behavior? Can't find it anywhere. Could you point me to the doc describing it?
I tried to grep something from a file and assign the result to the variable. So I did a=$(grep pattern file_not_exist)
. Then I see grep complained that the file does not exist. I wonder why this complaint message is not assigned to the variable rather than being printed out? Is it because of stdout and stderr?
Solution
No, it's not because the command failed that a
is empty.
The command didn't produce any output data, so there is no data to be captured in a
.
Revise the function to read:
f(){ echo Hello; return 1; }
Now run the command substitution. You'll find that a
contains Hello
. If you check $?
immediately after the assignment, it contains 1
, the status returned from the function. Exit statuses and command outputs are separate.
The documentation is in the GNU Bash manual for Command Substitution.
Answered By - Jonathan Leffler