Kevin Burke
Kevin Burke

Reputation: 64784

Send input to running shell script from bash

I'm writing a test suite for my app and using a bash script to check that the test suite output matches the expected output. Here is a section of the script:

for filename in test/*.bcs ;
do
    ./BCSC $filename > /dev/null
    NUMBER=`echo "$filename" | awk -F"[./]" '{print $2}'`
    gcc -g -m32 -mstackrealign runtime.c $filename.s -o test/e$NUMBER
    # run the file and diff against expected output
    echo "Running test file... "$filename
    test/e$NUMBER > test/e$NUMBER.out
    if [ $NUMBER = "4" ]
    then
        # it's trying to read the line
        # Pass some input to the file...
    fi
    diff test/e$NUMBER.out test/o$NUMBER.out
done

Test #4 tests reading input from stdin. I'd like to test for script #4, and if so pass it a set of sample inputs.

I just realized you could do it like

test/e4 < test/e4.in > test/e4.out

where e4.in has the sample inputs. Is there another way to pass input to a running script?

Upvotes: 2

Views: 5333

Answers (3)

Gordon Davisson
Gordon Davisson

Reputation: 125768

If you want to supply the input data directly in the script, use a here-document:

    test/e$NUMBER > test/e$NUMBER.out
    if [ $NUMBER = "4" ]; then
    then
        test/e$NUMBER > test/e$NUMBER.out <<END_DATA
test input goes here
you can supply as many lines of input as you want
END_DATA
    else
        test/e$NUMBER > test/e$NUMBER.out
    fi

There are several variants: if you quote the delimiter (i.e. <<'END_DATA'), it won't do things like replace $variable replacement in the here-document. If you use <<-DELIMITER, it'll remove leading tab characters from each line of input (so you can indent the input to match the surrounding code). See the "Here Documents" section in the bash man page for details.

Upvotes: 1

Jan
Jan

Reputation: 1837

You can do:

cat test/e4.in | test/e4 > test/e4.out

Upvotes: 0

Shai Deshe
Shai Deshe

Reputation: 153

The way you mentioned is the conventional method to redirect a file into stdin when issuing a command/script.

Maybe it'll help if you'll elaborate on the "other way" you're looking for, as in, why do you even need a different way to do so? Is there anything you need to do which this method does not allow?

Upvotes: 0

Related Questions