循环播放bash

时间:2018-03-23 18:58:10

标签: bash

我试图创建一个脚本来测试我的文件是否完全正确,但我之前没有使用过bash:

 #!/bin/bash
./myfile <test.in 1>>test.out 2>>testerror.out
if cmp -s "test.out" "pattern.out"
    then
        echo "Test matches pattern"
    else
        echo "Test does not match pattern"
    fi
if cmp -s "testerror.out" "pattern.err"
    then
        echo "Errors matches pattern"
    else
        echo "Errors does not match pattern"
    fi

我能否以这样的方式编写它:在调用./script.sh myfile模式后,我的脚本将运行在名为pattern * .in的所有文件上,并检查myfile是否提供与pattern * .out和pattern * .err相同的文件?例如,有文件pattern1,pattern2,pattern4,我想为它们运行测试,但不适用于不存在的pattern3。

我可以以某种方式创建新文件吗? (假设我不需要它们)如果我是从命令行开始的,我会选择像

这样的东西。
< pattern.in ./myfile | diff -s ./pattern.out

但我不知道如何在脚本文件中编写它以使其工作。

或许我应该每次都使用rm?

1 个答案:

答案 0 :(得分:1)

如果我理解正确的话:

for infile in pattern*.in ; do  
    outfile="${infile%.in}.out"
    errfile="${infile%.in}.err"

    echo "Working on input $infile with output $outfile and error $errfile"
    ./myfile <"$infile" >>"$outfile" 2>>"$errfile"
    # Your `if`..`fi` blocks here, referencing infile/outfile/errfile
done

%替换运算符从变量值的末尾删除子字符串。因此,如果$infilepattern.in,则${infile%.in}是没有尾随.in的,即patternoutfileerrfile分配使用此功能复制正在处理的特定pattern1文件的第一部分(例如.in)。

相关问题