How do I syntax check a Bash script without running it?

前端 未结 8 635
渐次进展
渐次进展 2020-11-28 00:16

Is it possible to check a bash script syntax without executing it?

Using Perl, I can run perl -c \'script name\'. Is there any equivalent command for ba

相关标签:
8条回答
  • 2020-11-28 01:03

    If you need in a variable the validity of all the files in a directory (git pre-commit hook, build lint script), you can catch the stderr output of the "sh -n" or "bash -n" commands (see other answers) in a variable, and have a "if/else" based on that

    bashErrLines=$(find bin/ -type f -name '*.sh' -exec sh -n {} \;  2>&1 > /dev/null)
      if [ "$bashErrLines" != "" ]; then 
       # at least one sh file in the bin dir has a syntax error
       echo $bashErrLines; 
       exit; 
      fi
    

    Change "sh" with "bash" depending on your needs

    0 讨论(0)
  • 2020-11-28 01:05

    I also enable the 'u' option on every bash script I write in order to do some extra checking:

    set -u 
    

    This will report the usage of uninitialized variables, like in the following script 'check_init.sh'

    #!/bin/sh
    set -u
    message=hello
    echo $mesage
    

    Running the script :

    $ check_init.sh
    

    Will report the following :

    ./check_init.sh[4]: mesage: Parameter not set.

    Very useful to catch typos

    0 讨论(0)
提交回复
热议问题