sachin
sachin

Reputation: 51

Shell script - check the syntax

How to check the correctness of the syntax contained in the ksh shell script without executing it? To make my point clear: in perl we can execute the command:

perl -c test_script.pl

to check the syntax. Is something similar to this available in ksh?

Upvotes: 5

Views: 10591

Answers (3)

Noj
Noj

Reputation: 66

The tests that you say failed to detect syntax errors, where not in fact syntax errors... echo is a command (OK a builtin, but still a command) so ksh/bash are not going to check the spelling/syntax of your command. Similarly "[" is effectively an alias for the test command, and the command expects the closing brace "]" as part of its syntax, not ksh/bash's. So -n does what it says on the tin, you just haven't read the tin correctly! :-)

Upvotes: 1

immnek
immnek

Reputation: 49

I did a small test with the following code:

#!/bin/bash
if [ -f "buggyScript.sh" ; then
    echo "found this buggy script"
fi

Note the missing ] in the if. Now I entered

bash -n buggyScript.sh

and the missing ] was not detected.

The second test script looked like this:

#!/bin/bash
if [ -f "buggyScript.sh" ]; then
    echo "found this buggy script"

Note the missing fi at at end of the if. Testing this with

bash -n buggyScript.sh

returned

buggyScript.sh: line 5: syntax error: unexpected end of file

Conclusion: Testing the script with the n option detects some errors, but by no means all of them. So I guess you really find all error only while executing the script.

Upvotes: 1

Gilbert
Gilbert

Reputation: 3776

ksh -n

Most of the Borne Shell family accepts -n. tcsh as well.

Upvotes: 4

Related Questions