Bash and Test-Driven Development

前端 未结 8 1762
礼貌的吻别
礼貌的吻别 2020-12-04 15:33

When writing more than a trivial script in bash, I often wonder how to make the code testable.

It is typically hard to write tests for bash code, due to the fact tha

8条回答
  •  一整个雨季
    2020-12-04 16:11

    The advanced bash scripting guide has an example of an assert function but here is a simpler and more flexible assert function - just use eval of $* to test any condition.

    assert() {
      if ! eval $* ; then
          echo
          echo "===== Assertion failed:  \"$*\" ====="
          echo "File \"$0\", line:$LINENO line:${BASH_LINENO[*]}"
          echo line:$(caller 0)
          exit 99
      fi  
    }
    
    # e.g. USAGE:
    assert [[ $r == 42 ]]
    assert "((r==42))"
    

    BASH_LINENO and caller bash builtin are bash shell specific.

提交回复
热议问题