Search code examples
bashexit-code

getting the error code of a sub-command using $(...)


In this code :

echo hello > hello.txt
read X <<< $(grep hello hello.txt)
echo $?

$? refers to the exit code of the read statement which is 0. Is there a way to know if the grep failed (e.g., if hello.txt has been deleted by another process) without splitting the read and grep in two statements (i.e., first grep then check $? then read).


Solution

  • Use process substitution instead of command substitution + here string:

    read X < <(grep 'hello' hello.txt)
    

    This will get you 1 when using echo $?.

    PS: If grep fails it will write an error on your terminal.

    If you want to suppress error then use:

    read X < <(grep 'hello' hello.txt 2>/dev/null)