2

I have a bash script I want to self-destruct on execution. So far it works great but I'd like some final check that if no errors have occurred (any output to stderr), then go ahead and self destruct. Otherwise, I'd like to leave the script in tact. I have the code for everything except the error check. Not sure if I can just output err to a file and check if file is empty. I'm sure it's a simple solution.

How could I do this?

Thanks for any help.

3
  • I'm not familiar with the command but looking it up it seems so. Does it provide the stderr output as well? I figured I can put set -e at the top of the script and if it gets to the rm -- "$0", then I'll assume it went great. Commented Mar 2, 2016 at 21:48
  • No, set -e has nothing to do with STDERR, it just deals with exit codes. Note though that just because a command prints to STDERR it doesn't mean that it has failed. A lot of commands just use it for logging. A command's exit code should indicate its success. Commented Mar 3, 2016 at 6:22
  • Oh, I get it now. Thanks for the explanation! Commented Mar 3, 2016 at 13:03

2 Answers 2

5

You can try this out. $? contains the return code for the process last executed by command. Moreover standard nix derivatives demarcate 0 as (no error) and 1 - 255 as some kind of errors that happened. Note that this will report errors that do not necessarily have any stderr output.

command
if [ "$?" -ne 0 ]; then
    echo "command failed";
    # your termination logic here
    exit 1;
fi
Sign up to request clarification or add additional context in comments.

Comments

4

Assuming that your script returns the value 0 on success, a value from 1 to 255 if an error occur you can use the following command

if /path/to/myscript; then
    echo success
else
    echo failed
fi

you can also use the following (shorter) command

[[ /path/to/myscript ]] &&  echo success || echo failed

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.