mora
mora

Reputation: 2287

How can I get the return value and matched line by grep in bash at once?

I am learning bash. I would like to get the return value and matched line by grep at once.

if cat 'file' | grep 'match_word'; then
  match_by_grep="$(cat 'file' | grep 'match_word')"
  read a b <<< "${match_by_grep}"
fi

In the code above, I used grep twice. I cannot think of how to do it by grep once. I am not sure match_by_grep is always empty even when there is no matched words because cat may output error message.

match_by_grep="$(cat 'file' | grep 'match_word')"
if [[ -n ${match_by_grep} ]]; then
  # match_by_grep may be an error message by cat.
  # So following a and b may have wrong value.
  read a b <<< "${match_by_grep}"
fi

Please tell me how to do it. Thank you very much.

Upvotes: 1

Views: 3274

Answers (3)

that other guy
that other guy

Reputation: 123450

When assigning a variable with a string containing a command expansion, the return code is that of the (rightmost) command being expanded.

In other words, you can just use the assignment as the condition:

if grepOutput="$(cat 'file' | grep 'match_word')"
then
  echo "There was a match"
  read -r a b <<< "${grepOutput}"
  (etc)
else
  echo "No match"
fi

Upvotes: 1

Inian
Inian

Reputation: 85560

You can avoid the double use of grep by storing the search output in a variable and seeing if it is not empty.

Your version of the script without double grep.

#!/bin/bash

grepOutput="$(grep 'match_word' file)"

if [ ! -z "$grepOutput" ]; then
    read a b <<< "${grepOutput}"
fi

An optimization over the above script ( you can remove the temporary variable too)

#!/bin/bash

grepOutput="$(grep 'match_word' file)"

[[ ! -z "$grepOutput" ]] && (read a b <<< "${grepOutput}")

Using double-grep once for checking if-condition and once to parse the search result would be something like:-

#!/bin/bash

if grep -q 'match_word' file; then
    grepOutput="$(grep 'match_word' file)"
    read a b <<< "${grepOutput}"
fi

Upvotes: 2

Ryota
Ryota

Reputation: 1305

Is this what you want to achieve?

grep 'match_word' file ; echo $?

$? has a return value of the command run immediately before.
If you would like to keep track of the return value, it will be also useful to have PS1 set up with $?.

Ref: Bash Prompt with Last Exit Code

Upvotes: 0

Related Questions