Search code examples
bashstderr

How can I use an if statement in bash to check if no errors have occurred?


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.


Solution

  • 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