5

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?

3 Answers 3

4

ksh -n

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

Sign up to request clarification or add additional context in comments.

5 Comments

It does not seem to be working. I executed ksh -n test.sh but it did not list out the syntax error which was there in test.sh
Yes it does work. I'm sure there is no syntax error. If you show us the script we can analyze if your expectations of finding a syntax error are correct.
Then try with sh -n script. It should work. However, if your syntax error is in an invalid command name, that would only get caught at run time. sh -n only checks the actual shell syntax.
Also some errors only show up at run time, even syntax errors. The trouble is that shells reparse each line each time the line executes... a classic "interpreter" behavior. Thus if any meta-characters (' " $, ... often ! ... ) are in a variable used in the line the characters can adversely impact late parsing. The first round of defense is to quote every $ variable, and if reading $*, understand and use the alternate "$@" notation (with the double quotes).
Jens : yes -n did not catch syntax errors like I changed echo to eco and sh -n did not report any syntax error
1

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.

Comments

1

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! :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.