使用diff时,Bash Script退出时没有错误

时间:2013-02-15 07:36:12

标签: bash diff exit

我很擅长使用bash,并且正在尝试创建一个用于运行某些测试用例的自动编程脚本。目前我的bash脚本似乎行为奇怪;当我有-e标志设置时,bash将在diff具有正大小时退出,并且当未设置-e标志时,脚本会忽略diff文件中的任何差异并且表示所有测试都已通过。

脚本在“write_diff_out = ....”命令后立即退出,不打印下一行。我只包含脚本的差异部分,因为其他一切运行正常(文件都存在)。

# Validate outputs and print results
echo "> Comparing current build's final memory output with golden memory output...";
for file in `ls test_progs`;
do
    file=$(echo $file | cut -d '.' -f1);
    echo "$file";
    write_diff_out=$(diff ./log/$file.writeback.out ./log/$file.writeback.gold.out > ./diff/$file.writeback.diff);
    echo "Finished write_diff";
    program_diff_out=$(diff -u <(grep -E '@@@' ./log/$file.program.out) <(grep -E '@@@' ./log/$file.program.gold.out) > ./diff/$file.program.diff);
    echo "Finished program diff";

    if [ -z "$write_diff_out" ] && [ -z "$program_diff_out" ]; then
        printf "%20s:\e[0;32mPASSED\e[0m\n" "$file";
    else
        printf "%20s:\e[0;31mFAILED\e[0m\n" "$file";
    fi
done
echo "> Done comparing test outputs.";

随意建议一种更好的格式化diff命令的方法,我知道有不同的编写方法。

1 个答案:

答案 0 :(得分:0)

我不知道你的问题是什么,但我已经重写了你的脚本以符合一些最佳实践。也许它会更好。

#!/bin/bash

# Debugging mode: prints every command as executed, remove when uneeded
set -x

# Validate outputs and print results
echo "> Comparing current build's final memory output with golden memory output..."

cd test_progs

for file in *; do
    file="$(echo "$file" | sed 's/\.[^.]*$//')"
    echo "$file"

    # will PASS when both diffs return non-zero

    if ! diff "log/$file.writeback.out" \
              "log/$file.writeback.gold.out" > \
              "diff/$file.writeback.diff" && \
       ! diff -u <(grep -E @@@ "log/$file.program.out") \
                 <(grep -E @@@ "log/$file.program.gold.out") > \
                 "diff/$file.program.diff"; then
        printf '%20s:\e[0;32mPASSED\e[0m\n' "$file"
    else
        printf '%20s:\e[0;31mFAILED\e[0m\n' "$file"
    fi
done

echo "> Done comparing test outputs."

它避免解析ls,use quotes where it is due,使用[[而不是[(你不需要在[[)中引用变量,并且它测试写入的文件是否为空而不是存储变量的东西。

如果你真的想将diff的输出存储在变量中,你可以这样做:

write_diff_out="$(diff "log/$file.writeback.out" "log/$file.writeback.gold.out" | tee "diff/$file.writeback.diff")"

然后$write_diff_out将包含diff/$file.writeback.diff文件所具有的相同数据。

编辑:编辑我的答案,在评论中实施一些内容。