0

So this is the gist: I have a script that execute various commands.

One of these commands, returns some logging, regarding the operation performed. I would like to intercept this logging and stop the script, if there is an error. Since the following operations in the script, are tied to the success of this operation, it makes no sense to run the whole script when you get an error at this phase.

This command is run on a remote computer via ssh; the idea would be to stop the script, as soon as the ssh command quit and the control goes back to the script

Is there a simple way to check the output of a command, which is running in a shell script? I could redirect the output to a file, and parse it, but this seems to add a lot of work extra on the script; while I need to trigger the exit only if there were errors in the ssh command.

What would you suggest to accomplish this task?

1 Answer 1

2

If the commands exits with an error code when there is an error, you can do something like this:

if ! ssh somehost mycommand; then
  echo "There was an error."
  exit 1
fi

If it doesn't provide a useful error code, then you'll probably need to check the output using something like:

if ssh somehost somecommand 2>&1 | grep error_message; then
  echo "There was an error."
  exit 1
fi

These are both very common techniques, and one or both may be applicable to your needs.

3
  • Much appreciated. The command do not return an error code sadly; so I have to look for specific keywords that would show up in the logs, which show that something went wrong on the remote operation and abort the script. Thanks a lot, I will give it a try !
    – user393267
    Commented Jan 22, 2014 at 1:36
  • It works partially; everything is fine, except that in the logs I just see printed the error string; while I need to retain the full log, and not only the error string. So basically the command runs, prints a bunch of log lines while running, and I need to have these printed too. Why is it printing only the error string? Because the output is passing trough grep?
    – user393267
    Commented Jan 22, 2014 at 1:47
  • 1
    That's correct -- because we're passing the output through grep, we're filtering out everything that doesn't match. If you need to preserve all the output, dump it to a file and then grep the file.
    – larsks
    Commented Jan 22, 2014 at 2:49