1

I'm trying to test a program (tp3) with several input files and printing the output in another file. So I've designed the following bash script name runner to do everything at the same time:

#!/bin/bash
rm $2
clear
FILES=(`ls ${1}`)
cmd='./tp3'
for f in ${FILES[*]}
do
    echo "$f"
    echo "--------------<$f>--------------" >> $2
    $cmd < $1$f 2>> $2 >> $2
done 

Everytime I run this script I get the following error:

./runner: line 10: $2: ambiguous redirect
./runner: line 11: testtest: No such file or directory

To run the bash script I do:

./runner test

What is wrong in the script?

Modifications to make it work: First of all I've quoted the variables, then I've replaced the second argument "$2" for a file named "TEST" and now everything is working just fine.

New code:

#!/bin/bash
rm TEST
clear
FILES=(`ls *.in`)
cmd='./tp3'
for f in ${FILES[*]}
do
    echo "$f"
    echo "--------------<"$f">--------------" >> "TEST"
    "$cmd" < "$1$f" >> "TEST" 2>> "TEST"
done

Thanks everyone for your help.

Jens
  • 69,818
  • 15
  • 125
  • 179
tul1
  • 412
  • 1
  • 6
  • 22
  • 1
    Try `$cmd < $1$f >> $2 2>&1`. Although that won't fix it, it's better practice. Your problem is that `$2` doesn't exist. You're only supplying one argument... By the way, storing commands in a variable is bad practice, as is looping over files using that kind of for loop construction. You're better of using `find` but that's just an FYI. – ShellFish May 09 '15 at 23:48
  • 1
    Quote your variables! That will also get you [better error messages](http://stackoverflow.com/questions/2462385/getting-an-ambiguous-redirect-error). I suspect `$1$f` should be `"$1/$f"`, and put `"$2"` instead of `$2` everywhere. – Wintermute May 09 '15 at 23:50

1 Answers1

1

You are running ./runner test in which test is $1 and $2 is empty. Your redirection is therefor illegal. Also try to couple stdout and stderr when pointing to the same output. This can be done as follows: command arguments > output 2>&1. This will send stderr output to where ever the stdout output is sent.

Also, as Wintermute pointed out: quote variables. Spaces in variables will make it be interpreted as separate arguments. e.g. command $1 supplies two arguments to command if $1 equals some string for example.

This translates into the following: you use $f if this contains a space it will split the argument and everything after the space will be treated as extra arguments or commands rather than one single argument.

Jens
  • 69,818
  • 15
  • 125
  • 179
ShellFish
  • 4,351
  • 1
  • 20
  • 33