2

我对使用 bash 相当陌生,并试图创建一个自动评分器脚本来运行一些测试用例。目前我的 bash 脚本似乎表现得很奇怪;当我设置了 -e 标志时,当 diff 的大小为正时,bash 将退出,而当未设置 -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 命令的方法,我知道有不同的方法来编写它们。

4

1 回答 1

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,在到期时使用引号,使用[[而不是[(您不需要在[[)中引用变量,并且它测试写入的文件是否为空,而不是在变量中存储一些东西。

如果您真的想将 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文件具有的相同数据。

编辑:稍微编辑我的答案,以实现评论中的一些内容。

于 2013-02-15T08:38:11.643 回答