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

前端 未结 8 634
渐次进展
渐次进展 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 00:48

    null command [colon] also useful when debugging to see variable's value

    set -x
    for i in {1..10}; do
        let i=i+1
        : i=$i
    done
    set - 
    
    0 讨论(0)
  • 2020-11-28 00:50

    I actually check all bash scripts in current dir for syntax errors WITHOUT running them using find tool:

    Example:

    find . -name '*.sh' -exec bash -n {} \;

    If you want to use it for a single file, just edit the wildcard with the name of the file.

    0 讨论(0)
  • 2020-11-28 00:55
    sh  -n   script-name 
    

    Run this. If there are any syntax errors in the script, then it returns the same error message. If there are no errors, then it comes out without giving any message. You can check immediately by using echo $?, which will return 0 confirming successful without any mistake.

    It worked for me well. I ran on Linux OS, Bash Shell.

    0 讨论(0)
  • 2020-11-28 00:58

    Time changes everything. Here is a web site which provide online syntax checking for shell script.

    I found it is very powerful detecting common errors.

    enter image description here

    About ShellCheck

    ShellCheck is a static analysis and linting tool for sh/bash scripts. It's mainly focused on handling typical beginner and intermediate level syntax errors and pitfalls where the shell just gives a cryptic error message or strange behavior, but it also reports on a few more advanced issues where corner cases can cause delayed failures.

    Haskell source code is available on GitHub!

    0 讨论(0)
  • 2020-11-28 00:58

    There is BashSupport plugin for IntelliJ IDEA which checks the syntax.

    0 讨论(0)
  • 2020-11-28 01:02
    bash -n scriptname
    

    Perhaps an obvious caveat: this validates syntax but won't check if your bash script tries to execute a command that isn't in your path, like ech hello instead of echo hello.

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