2

I am a beginner with bash so I apologize if this is a basic question or has syntax issues but I couldn't find the answer anywhere. I want to run a command, and if it fails, check if the error message matches a certain string. Here is what I have:

err_msg=`./command input.txt 2>&1`
if [$? -eq 1]
then 
   if [err_msg -eq "Error: timeout"]
   then
       #do something
   fi
fi

Is this the correct way to do this? If I'm using the first line to define the error message err_msg, will $? still store the pass/fail status of the command? Also, what will happen to if the command passes? Will err_msg just be blank?

  • You have some syntax errors: 1. leave a space around the characters `[` and `]`: these are builtins and need to have a space around them to be recognized as such. 2. Don't use `-eq` to test for equality of strings. Use `=` instead. Re. your question: yes, `$?` will expand to the return code of the command. – gniourf_gniourf Dec 02 '17 at 17:50
  • Thank you! Also, should err_msg be $err_msg in the 2nd if statement since it's a variable? – Sophie Foreman Dec 02 '17 at 17:52
  • Yes, of course, you want to check for _the expansion_ of `err_msg`. You also need to _quote_ this expansion: `"$err_msg"`, unless you use the more robust keyword `[[`. – gniourf_gniourf Dec 02 '17 at 17:54
  • That is helpful, thank you! – Sophie Foreman Dec 02 '17 at 18:09

1 Answers1

1
  • Don't use the old-style backquote form of command substitution, use $(command) instead
  • Use [[ ]] for testing instead of [ ] as it has more features and fewer surprises
  • -eq is used for integer comparison. For string comparison, use = or ==
  • Note that command can fail with an exit status other than 1, thus it's better to test for non-zero status: ! [[ $? -eq 0 ]]
  • You can use $? for testing exit status of the last command or you can test it with if directly: if command; then echo CMD OK; fi
  • You can assign output of a command to a variable while testing its exit code

Using the points above, you can rewrite your code like this:

if ! err_msg=$(./command input.txt 2>&1)
then 
   if [[ $err_msg = "Error: timeout" ]]; then
      echo "Doing something.."
   fi
fi
PesaThe
  • 7,259
  • 1
  • 19
  • 43