LamaEu
LamaEu

Reputation: 71

Ambiguous redirect ERROR when trying to loop through a file

I have this script:

#!/bin/bash

PATH=${PATH[*]}:.
#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 file.txt in testScript it works just fine.
How do I make it treat $1 as the file name I send? (file.txt)

Upvotes: 0

Views: 1219

Answers (3)

CWLiu
CWLiu

Reputation: 4043

Modify your while loop as followed,

while read line; do
.
.
.
done < "${1:-/dev/stdin}"

${1:-...} takes $1 if it's defined otherwise the file name of the standard input of the own process is used.

Upvotes: 1

chepner
chepner

Reputation: 531055

$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
    ...
done

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.

Upvotes: 1

Cyrus
Cyrus

Reputation: 88583

Replace < ./file.txt by ./file.txt.

Upvotes: 1

Related Questions