3

I'm trying to make a script that would test whether my file is exactly as it should be, but I haven't been using bash before:

 #!/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

Can I write it in such way that after calling ./script.sh myfile pattern my scripts would run over all files named pattern*.in and check if myfile gives same files as pattern*.out and pattern*.err ? e.g there are files pattern1, pattern2, pattern4 and i want to run test for them, but not for pattern3 that doesn't exist.

Can I somehow go around creating new files? (Assuming i don't need them) If I were doing it from command line, I'd go with something like

< pattern.in ./myfile | diff -s ./pattern.out

but I have no idea how to write it in script file to make it work.

Or maybe i should just use rm everytime?

4
  • Use a for loop to iterate over all the files that match the pattern. Commented Mar 23, 2018 at 19:39
  • for file in pattern*.in Commented Mar 23, 2018 at 19:40
  • You can use variables like < "$file" ./myfile Commented Mar 23, 2018 at 19:41
  • Welcome to the site! Check out the tour and the how-to-ask page for more about asking questions that will attract quality answers. You can edit your question to include more information. Do you mean you want to be able to provide myfile and pattern as command-line parameters to script.sh? Commented Mar 23, 2018 at 22:46

1 Answer 1

1

If I understand you correctly:

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

The % replacement operator strips a substring off the end of a variable's value. So if $infile is pattern.in, ${infile%.in} is that without the trailing .in, i.e., pattern. The outfile and errfile assignments use this to copy the first part (e.g., pattern1) of the particular .in file being processed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.