2

I need to pass yes or no input to a bash script. It works for single single input using yes, however if the bash script has multiple input (more than one) how can I pass it ? Below is the example for a single yes input:

yes | ./script 

I can't send as below if the script needs different input, for instance:

yes | no | ./script 
0

4 Answers 4

8

Shortly, using yes

yes is a tool for repeating some string infinitely.

You can pass 1 yes, then 1 no, then again 1 yes and 1 no and so on by using:

yes $'yes\nno' | ./script.sh 

Using , you could reverse the pipe by using process-substitution syntax:

./script < <(yes $'yes\nno') 

Sample:

head -n 6 < <(yes $'yes\nno') 
yes no yes no yes no 

... or two yes and one no:

head -n 6 < <(yes $'yes\nyes\nno') 
yes yes no yes yes no 

Or any other combination...

Further

As your question stand for:

If the bash script has multiple input (more than one) how can I pass it ?

Little sample (using a function instead of a script, for demo):

myScript() { while read -rp 'Name: ' name && [[ -n $name ]]; do read -rp 'Last name: ' lName || break read -rp 'Birth date (YYYY-MM-DD): ' birth || break bepoch=$(date -d "$birth" +%s) printf 'Hello %s %s, you are %d years old.\n' \ "$name" "$lName" $(((EPOCHSECONDS-bepoch)/31557600)) done } 

Sample run:

myScript 
Name: John Last name: Doe Birth date (YYYY-MM-DD): 1941-05-03 Hello John Doe, you are 83 years old. 

Using inline string

myScript <<<$'John\nDoe\n1941-05-03' 
Hello John Doe, you are 83 years old. 

Using inline text

myScript <<eoInput John Doe 1941-05-03 James Bond 1953-04-13 eoInput 
Hello John Doe, you are 83 years old. Hello James Bond, you are 72 years old. 
Sign up to request clarification or add additional context in comments.

Comments

7

yes sends y (or whatever else you tell it to send) to its standard output. If you want yes and no on the standard output, you can use echo:

{ echo yes echo no } | ./script 

I used a block to pipe both inputs to the script. There are more possible ways, e.g.

printf '%s\n' yes no | ./script.sh 

Comments

4

We can also use below command also

echo -e "yes\nno" | ./script.sh 

Comments

0

You can just send the lines you want -

printf "yes\nno\n" | ./script.sh 

or if you need a certain number of each -

{ yes yes |head -50; yes no | head -50; } | ./script.sh 

Or if you need them toggled -

yes | awk '{ if (NR%2) {print "yes"} else {print "no"} }' | ./script.sh 

(only using yes here as a driver for records to read, lol)

1 Comment

I like F. Hauri's better. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.