1

How do i check for errors (and maybe warnings) in a bash script?

I want to precheck bash scripts before checking them into a git repository.

I know I can use bash -n script.sh for a first, simple check but this doen't find for example things like rewriting on a readonly string.

readonly unique_id = "42"
unique_id = "21"

will be ok for a bash -n script.sh but will fail on execution of course.

EDIT: the following script

#!/bin/bash
# check.sh
readonly unique_id="42"
unique_id="21"

give 0 if you execute bash -n check.sh; echo $? but execution itself results in the error message ./check.sh: line 4: unique_id: readonly variable

Both behaviors are correct because this is not a syntax error but it will still break execution (even in unit tests) and I am asking if there is another way of precheck to filter out such errors.

Unittest will find only expected logical failures so this is not an alternative.

2
  • 2
    The two lines posted above are erroneous. You need to remove spaces surrounding =. Commented Aug 12, 2013 at 8:57
  • Yep, you are right; I removed the blanks and add a shebang to get a real world example. Thanks Commented Aug 16, 2013 at 6:18

2 Answers 2

0

I assume you consider just run that script to check for errors? Then, if you wouldn't do some "errors" message to stdout, you could also check for last exit status code in bash: $?. (http://blog.yimingliu.com/2009/01/01/check-last-exit-status-code-in-bash-shell/)

Sign up to request clarification or add additional context in comments.

Comments

0

Another way is to place all your codes inside functions. That way you would be able to run your code and check for syntax errors before calling the main function:

#!/bin/bash

function A {
    ...
}

function B {
    ...
}

function main {
    # most of your codes here
    ...
}

# main "$@"

Uncomment the last line if no syntax errors were found. Of course there are exemptions like those executed on eval, nested paramater expansions or expansions basing on a runtime value, some which are based on arguments to a builtin command, and other errors found during runtime.

1 Comment

But you still execute the code...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.