测试 bash shell 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5382768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:18:34  来源:igfitidea点击:

Testing a bash shell script

bashshell

提问by Mr Teeth

Can someone explain how to test for a bash shell script?

有人可以解释如何测试 bash shell 脚本吗?

For example i've got a .sh file with this code in it...

例如,我有一个包含此代码的 .sh 文件...

#!/bin/sh

for file in *.txt; do
    mv "$file" "`basename $file .txt`.doc"
done

How do I write a test for it? Like in Java you've got unit testing where you write code like assertEquals to test the code gives the desired output.

我如何为它编写测试?就像在 Java 中一样,您进行了单元测试,您可以在其中编写诸如 assertEquals 之类的代码来测试代码是否提供所需的输出。

回答by Mark Nenadov

You can do asserts in Bash. Check out this from the Advanced Bash-Scripting Guide:

您可以在 Bash 中进行断言。从高级 Bash 脚本指南中查看:

http://tldp.org/LDP/abs/html/debugging.html#ASSERT

http://tldp.org/LDP/abs/html/debugging.html#ASSERT

回答by Mark

Try this out: assert.sh

试试这个:assert.sh

source "./assert.sh"

local expected actual
expected="Hello"
actual="World!"
assert_eq "$expected" "$actual" "not equivalent!"
# => x Hello == World :: not equivalent! 

回答by geekosaur

I'd add an echoin front of the mvto verify that the right commands are being created, for starters. (Always a good idea with commands that make possibly difficult to undo changes.)

对于初学者,我会echo在 前面添加一个mv以验证是否正在创建正确的命令。(对于可能难以撤消更改的命令,这总是一个好主意。)

Some possibly useful resources:

一些可能有用的资源: