1

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.

mora
  • 2,217
  • 4
  • 22
  • 32

3 Answers3

2

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
Inian
  • 80,270
  • 14
  • 142
  • 161
1

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
that other guy
  • 116,971
  • 11
  • 170
  • 194
0

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

Community
  • 1
  • 1
Ryota
  • 1,157
  • 2
  • 11
  • 27
  • thank you for answering. I would like to read(or analyze) matched line only when the file has the line including matched word. To do it, I used grep twice, but I feel it is not efficient. I would like to do it by only one grep if possible. – mora Nov 17 '16 at 10:36
  • @mora sorry misunderstood your intention - if you would like to analyze further on grep output only when matched word is found, you can evaluate $? right after the grep: – Ryota Nov 17 '16 at 11:12
  • @Ryota : I thank you for answering to my ambiguous question. – mora Nov 17 '16 at 11:25