Testing Bash Script Syntax Before Running

The terminal based editors for bash scripts do not usually point out any errors in bash script syntax. You can often make mistakes when creating a complicated syntax or editing long scripts. It would be good to have bash script checked for syntax before running it or before checking into source control management systems, so as to prevent any last minute issues.

For this issue, we can use bash -n syntax. Let’s see what happens if we run this on a well structured script:

Source code for our script:

#!/bin/bash
# removes all docker containers on the local computer
CID=$(docker.exe ps --all --quiet)
for item in $CID
do 
   echo "Stopping and removing container id $item ..."
   docker.exe rm $item --force 2&>1
done

Output:

$ bash -n rm-containers.sh
$

Let’s modify the ending double quotes from line containing echo statement. So our faulty code becomes like this:

#!/bin/bash
# removes all docker containers on the local computer
CID=$(docker.exe ps --all --quiet)
for item in $CID
do 
   echo "Stopping and removing container id $item ...
   docker.exe rm $item --force 2&>1
done

If we now run bash -n, we can see below errors:

$ bash -n rm-containers.sh
 rm-containers.sh: line 6: unexpected EOF while looking for matching `"'
 rm-containers.sh: line 9: syntax error: unexpected end of file

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s