Debugging Bash Scripts - Part 2 - Using exit

Here is the list of all the Bash debugging posts:

The exit command in a Bash scrip will immediatly cause the scrip to stop as soon it is exit is executed.

This is very useful in two ways:

  1. This can be used to stop the scrip immediatly after your problem section all the remaining script doesn’t get run.
  2. You can put it into a loop so that it only performs one iteration.

Using the script from Part 1:

#!/bin/bash

# Set a variable for the directory we want to search in
dir="files/"

# Find all the files in the files directory
files=$(find "$dir" -type f)

#Echo the file list
echo "$files"

We can stop the scrip from executing the echo command by putting in an exit before it:

#!/bin/bash

# Set a variable for the directory we want to search in
dir="files/"

# Find all the files in the files directory
files=$(find "$dir" -type f)

exit

#Echo the file list
echo "$files"

The other use is to force a loop to execute a single time. The following script has a simple for loop:

#!/bin/bash

# Echo each file that is found in the files/ directory
for file in $(find "files/" -type f); do
    echo "File = ""$file"""
done

This prints the following:

$ ./loop.sh
File = files/1.txt
File = files/2.txt
File = files/3.txt
File = files/4.txt
File = files/5.txt
File = files/6.txt
File = files/7.txt
File = files/8.txt
File = files/9.txt
File = files/10.txt

Loops can sometimes take a long time or have very long output which can make them difficult to work on. Putting an exit in the loop will cause it to run only a single iteration:

$ cat loop.sh
#!/bin/bash

# Echo each file that is found in the files/ directory
for file in $(find "files/" -type f); do
    echo "File = ""$file"""
    exit
done

This now prints the following:

$ ./loop.sh
File = files/1.txt