Using Syntax Checking

When dealing with any shell script, it is a good idea to check the syntax of the script before trying to execute it. This will help you find and fix most problems.

To enable syntax checking, use the -n option as follows:

/bin/sh -n script
						arg1
						arg2 ... argN
					

Here script is the name of a script and arg1 through argN are the arguments for that script. If there are syntax errors in script, the shell generates an error message that indicates the source of the error.

Check the syntax of the following script (the line numbers are included for your reference) and see if you can spot the error:

1  #!/bin/sh
2
3  YN=y
4  if [ $YN = "yes" ]
5      echo "yes"
6  fi

If this script is stored in the file buggy1.sh, you can check its syntax ...

Get Sams Teach Yourself Shell Programming in 24 Hours, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.