Sam
Sam

Reputation: 2331

How do I pass arguments to a bash script using a pipe?

I want to pass an argument to a read command within this script via a pipe or some other method.

My command within the script is

read -p "Change Parameters?
while [ $REPLY != "n" ]
do
        if  [ $REPLY == "a" ]
        then
..
..
        if [ $REPLY =="j" ]
..
done

The read command appears on line 48 of my script if thats of any use

I've tried

./script argument1 argument2 | bash /dev/stdin "n"

which results in

Change Parameters? /dev/stdin: line 1: Default: command not found
/dev/stdin: line 2: a: command not found
/dev/stdin: line 3: b: command not found
/dev/stdin: line 4: c: command not found
/dev/stdin: line 5: d: command not found
/dev/stdin: line 6: e: command not found
/dev/stdin: line 7: f: command not found
/dev/stdin: line 8: g: command not found
/dev/stdin: line 9: h: command not found
/dev/stdin: line 10: i: command not found
/dev/stdin: line 11: j: command not found
/dev/stdin: line 12: n: command not found

And then stops

I just want to pass the letter n to this command and for the script to continue till the end.

Upvotes: 0

Views: 7491

Answers (2)

George Vasiliou
George Vasiliou

Reputation: 6335

If you don't want to follow the echo way (echo something and pipe it to your script) you just need to change your command:

./script argument1 argument2 | bash /dev/stdin "n"

To

./script argument1 argument2 <<<"n"

Or

./script argument1 argument2 <<<"$var"

Upvotes: 2

Daniel
Daniel

Reputation: 528

Your pipe is the wrong way around, to pass n to the script you need to write

echo "n" | ./script argument1 argument2

Another example:

echo "abcd" | { read -p "Change Parameters?" b; echo $b; }

Output:

abcd

In the second example the { ... } part is your script, echo "abcd" is piped to the script, read gets the "abcd" (the prompt Change parameters? is not shown), saves it in the variable $b, then $b is echoed.

Upvotes: 2

Related Questions