LamaEu LamaEu - 8 months ago 54
Bash Question

Ambiguous redirect ERROR when trying to loop through a file

I have this script:


#filename: testScript

while read line; do

done < "$1"

And this text file(called file.txt):

I am a proud sentence.

And when I do:

chmod +x ./testScript.txt

./testScript.txt < ./file.txt > output.txt

I get this:

./testScript.txt: line 11: $1: ambiguous redirect

However, if I replace $1 with
it works just fine.

How do I make it treat $1 as the file name I send? (file.txt)


$1 isn't defined because you haven't passed an argument to your script; you've redirected its input. Either call your script as

./testscript.txt ./file.txt > output.txt

or, better yet, just let your script read from standard input:

while read line; do

When you call ./testScript < ./file.txt > output.txt, your while loop will read from its standard input, which is inherited from ./testScript, which reads from ./file.txt.