Bash and Test-Driven Development

前端 未结 8 1781
礼貌的吻别
礼貌的吻别 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:03

    If you are writing code at the same time with tests, try to make it high on functions that don't use anything besides their parameters and don't modify environment. That is, if your function might as well run in a subshell, then it will be easy to test. It takes some arguments and outputs something to stdout, or to a file, or maybe it does something on the system, but caller does not feel side effects.

    Yes, you will end up with big chain of functions passing down some WORKING_DIR variable that might as well be global, but this is minor inconvenience comparing to the task of tracking what does each function read and modify. Enabling unit tests is just a free bonus too.

    Try to minimize cases where you need output. A little subshell abuse will go long way to keeping things nicely separated (at the expense of performance).

    Instead of linear structure, where functions are called, set some environment, then other ones are called, all pretty much on one level, try to go for deep call tree with minimum data going back. Returning stuff in bash is inconvenient if you adopt self-imposed abstinence from global vars...

提交回复
热议问题