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

前端 未结 8 656
渐次进展
渐次进展 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

提交回复
热议问题