1

I'm trying to return a custom exit code (and subsequently display an error message) when there is no match for the value I'm trying to find. I found the following previous stackoverflow question - Return code of sed for no match, which I used to develop the following script.

update_value() {
  local before="$1"
  local after="$2"

  sed -i "/$before/!{q100}; {s/$before/$after/}" "$3"
  local sed_exit_code="$?"
  if [[ "$sed_exit_code" -eq 100 ]]; then
      echo "ERROR: There is no $before value in $3"
      exit 1
  elif [[ "$sed_exit_code" -ne 0 ]]; then
      echo "Error updating $before value in $3"
      exit 1
  else
      echo "Successfully updated $before to $after in $3"
  fi
}

update_value x y file.txt

I'm running this on CentOS Linux release 7.7.1908 (Core), with sed version (sed (GNU sed) 4.2.2), and it is returning the first error (ERROR: There is no x value in file.txt) despite there definitely being an x value in that file.

Therefore, sed is returning exit code 100 incorrectly. What am I missing/doing wrong here?

  • 2
    `/$before/!{q100}` means that if there's a line that doesn't match `$before`, exit. It doesn't mean to exit if there's no line that matches. – Barmar Nov 15 '19 at 00:46
  • So you'll get the error code unless *all* lines match `$before`. – Barmar Nov 15 '19 at 00:47
  • Ahhh ok, thanks @Barmar!! So, how do I check the file as a whole, rather than each individual line? Can I do that using sed? – Chris Fowler Nov 15 '19 at 00:52
  • 2
    You can check the whole file with `if grep -q "$before" "$3"`. Checking for `$before` before `$after` is probably better done using `awk`. – Barmar Nov 15 '19 at 00:55
  • cool, I'll have a play with these options. Thanks very much for your help – Chris Fowler Nov 15 '19 at 00:58
  • 2
    Since the script is using inplace editing (-i) , forcing early exit from sed (e.g. `q100`) will have the (serious) side effect of truncating the file, and losing all data after the first non-match. Going with separate `grep` for testing is the smart thing to do – dash-o Nov 15 '19 at 05:38
  • Thanks @dash-o, I did notice this happening when I put in extra logging. I have created two separate steps as suggested, and it's working as I wanted. Cheers! – Chris Fowler Nov 17 '19 at 23:14

0 Answers0