Bash How to Stop Script

Bash How to Stop Script

If you want to stop the bash script, that is currently running, you can do the 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 are currently running. Grep will filter the name that you want to kill. You should be very specific, in another word, the whole name of the process name should be used here. Grep -v grep will filter grep process. AWK will filter the second column from the output, that is PID (process id).

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

exit 45

This line exits your script and gives 45 to the parent process. You can choose a 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 the script) -e parameter:

#!/bin/bash -e
...
command1
command2
command3

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

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

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

echo $?

Bash will print integer values between 0 and 255.

Leave a Comment