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.

user762353
  • 155
  • 1
  • 7

2 Answers2

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/)

IProblemFactory
  • 9,551
  • 8
  • 50
  • 66
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.

konsolebox
  • 72,135
  • 12
  • 99
  • 105