bash how to stop script


If you want to stop bash script, that is currently running, you can do following sentence in bash:

kill $(ps aux | grep name_of_scirpt | grep -v  grep | awk '{ print $2 }')

Command ps aux will give you all processes that is currently running. Grep will filter name that you want to kill. You should be very specific, in another words, whole name of process name should be used here. Grep -v grep will filter grep process. AWK will filter second column from output, that is PID (process id).

If you want to stop script on specific line, just add

exit 45

This line exits your script and gives 45 to parent process. You can choose number between 0 - 255. Number 0 is special, it means that your script exits without any problem. Any number between 1 - 255 means that something wrong happens in your script.

If you want to stop your script, if 1st error occurs, just add in hashpling line (1st line of script) -e parameter:

#!/bin/bash -e

This script will terminate immediately, if some line fails. What means, that line of script fails? It means that line will exit with non-zero exit code (1-255). For example, if command2 fails (return non-zero exit code), command3 will not executed, at all.

I love this option in test environment. It helps me to avoid unnecessary script execution after failure. I also like bash -u parameter that exit your script if you use uninitialized shell variable.

If you want to get exit code of last command enter:

echo $?

Bash will print integer value between 0 and 255.