Skip to content

How to exit Bash script?

  • by
  • 3 min read

When coding any script, let alone Bash, having an exit clause in your script is a good coding practice. If you need to terminate your script based on a condition or after a certain action based on the exit code of the command, these clauses come in handy.

In this article, we’re going over the Bash exit command. We’ll be taking a look at how you can use this command and exit statuses of executed commands to terminate a Bash script. 

Also read: How to install Kali Linux on Virtualbox?


Bash exit status

Regardless of successful termination, each shell command returns an exit code. By default, non-zero error codes mean that there was some problem with the execution. 

The $? variable returns the exit status of the last executed command. For example, if you run ls on a non-existent directory, the return code will be non-zero. 

ls /no_dir &> /dev/null
echo $?

When you’re running multiple commands in a pipeline, the exit status is that of the last command executed.

sudo tcpdump -n -l | tee file.out
echo $?

The above set of commands will return the exit status of the tee command.

Also read: How to remove a Directory in Linux?


Bash exit command

The exit command exits the shell with the status provided.

exit N

In the above command, the script will end when encountering the status code. If no code is provided, the command uses the error code of the last executed command. 

When you use this command in a shell script, the error code returned is of the last executed command. 

Examples

You can use the exit command in conjunction with statements like if. The following example terminates the script if the specified string is found in a filename. 

if grep -q "search-string" filename then
  echo "String found."
else
  echo "String not found."
fi

If you’re running a list of commands using conditional operators like && or ||, the command’s exit status determines whether the condition is true or not. In the example below, the mkdir command will only execute if the cd command executes and returns 0. 

cd /opt/code && mkdir project

Below is an example of what will happen if a script is run by a non-root user. 

#!/bin/bash

if [[ "$(whoami)" != root ]]; then
  echo "Only user root can run this script."
  exit 1
fi

echo "doing stuff..."

exit 0

Now if you run this script as root, the exit code will be 0, otherwise, you’ll get 1.

Also read: Mint vs Ubuntu: Linux distro comparison

Yadullah Abidi

Yadullah is a Computer Science graduate who writes/edits/shoots/codes all things cybersecurity, gaming, and tech hardware. When he's not, he streams himself racing virtual cars. He's been writing and reporting on tech and cybersecurity with websites like Candid.Technology and MakeUseOf since 2018. You can contact him here: yadullahabidi@pm.me.

>
Exit mobile version