2

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

4
  • Why read X <<< $()? Why not just X=$()? What part of read do you need? Commented Oct 15, 2020 at 7:02
  • My mystake, this was a silly example. Basically I want to do something like command $(grep hello hello.txt) and then check if the grep succeeded. Commented Oct 15, 2020 at 7:16
  • Use a temporary variable. tmp=$(grep hello hello.txt); grep_exit_status=$?; command "$tmp". Commented Oct 15, 2020 at 7:17
  • Thanks for your answer. I'll do that. But I was wondering if there is some form of "stack of return codes" to get codes of older commands. Commented Oct 15, 2020 at 7:23

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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"

1 Comment

You guys are quick!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.