qouify
qouify

Reputation: 3900

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).

Upvotes: 2

Views: 302

Answers (2)

KamilCuk
KamilCuk

Reputation: 140960

Just:

X=$(grep hello hello.txt)
echo $?

For general case where you want to use read to do word splitting, then use a temporary variable:

tmp=$(grep hello hello.txt)
echo $?
IFS=' ' read -r name something somethingelse <<<"$tmp"

Upvotes: 2

anubhava
anubhava

Reputation: 785008

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)

Upvotes: 5

Related Questions