How to check the syntax of a Bash script without running it in Linux?

LinuxOperating SystemOpen Source

There are always chances that we will make some type of error whenever we are programming. Compilers and interpreters are always there to help us in these cases, but in order to use them we must run the program or some sort of an IDE that constantly checks for these errors and reminds us every time, so that we can correct them.

What if we don’t want to write our code in a fancy IDE and also don’t want to run the program either, in that case we are left with very few options if any. In case you are writing a bash script we can certainly check if the bash script has any syntax errors or not.

It should be noted that the syntax errors that we will be able to detect will only be the compile time errors and not the run time errors.

Example

Let’s explore an example. Assume we have a bash script which contains a code something like this −

for f in *.txt; do mv "$f" "${f// /_}"; done

The above code is simple, it just loops over all the .txt files present in the current directory and then changes the names of the files which contain spaces between them, as it replaces the spaces with the _(underscores).

This works like a charm, now when we run the command to check whether the above bash script has any syntax error, we won’t get any output.

Let’s explore this particular case −

Run the following command in your terminal, where the sample.sh is also present.

bash -n sample.sh

When I run this command, the terminal will simply print nothing.

Now let’s make a change to our sample.sh which will make it an invalid bash script and then we will run the same command again in the terminal.

for f in *.txt; do mv "$f" "${f// /_}"; done = true

Now when we run the following command shown below −

bash -n sample.sh

The output will be −

immukul@192 linux-questions-code % bash -n sample.sh
sample.sh: line 1: syntax error near unexpected token `='
sample.sh: line 1: `for f in *.txt; do mv "$f" "${f// /_}"; done = true'

That’s how we are able to check for syntax errors without even running it. Now, we talked about the fact that this command will only detect the compile time error and not the runtime error, and we can confirm it by changing the sample.sh again −

for d in *.txt; do mv "$f" "${f// /_}"; done

Now when we run the command shown below on the sample.sh file shown above −

bash -n sample.sh

The output will be nothing.

So, the final take is that you should use the command only if you want to check for syntax error.

raja
Published on 29-Jul-2021 11:43:59
Advertisements