How do I syntax check a Bash script without runnin

2020-01-25 03:17发布

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 bash scripts?

8条回答
放我归山
2楼-- · 2020-01-25 03:32

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

查看更多
神经病院院长
3楼-- · 2020-01-25 03:43
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.

查看更多
爷、活的狠高调
4楼-- · 2020-01-25 03:44

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

查看更多
疯言疯语
5楼-- · 2020-01-25 03:45

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!

查看更多
smile是对你的礼貌
6楼-- · 2020-01-25 03:45

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

查看更多
Animai°情兽
7楼-- · 2020-01-25 03:50

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 - 
查看更多
登录 后发表回答