1

I have a bash script which run a command to get its result and do something depends on the result. Here is the script:

#!/bin/bash
commandResult=$(($myCommand) 2>&1)
if [[ "$commandResult" == *Error* ]]; then 
    x="failed"
else
    x="success"
fi
echo $x
exit 0;

There is no problem with this script, the issue is when I try to kill $myCommand in the middle of running the script via kill -9 $myCommand in command line, the $commandResult will be null and the "success" will be printed.

How could I put the kill result in the $commandResult or any other way to find out if process killed in this script?

Any help would be much appreciated.

1 Answer 1

3

You should be checking your command's exit code, not its output to standard error. myCommand should exit with 0 on success, and some non-zero code on failure. If it is killed via the kill command, it's exit code will automatically be 128+n, where n is the signal you used to kill it. Then you can test for success with

if myCommand; then
    echo success
    exit 0
else
    status=$?
    echo failure
    exit $status
fi

Also, you probably don't need to use kill -9. Start with kill (which sends the gentler TERM signal); if that doesn't work, step up to kill -2 (INT, equivalent of Ctrl-C).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.