Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass YES and NO sequentially to a bash script

Tags:

linux

bash

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
like image 376
kirthan shetty Avatar asked Jan 26 '26 23:01

kirthan shetty


2 Answers

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 bash, 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.
like image 136
F. Hauri Avatar answered Jan 28 '26 12:01

F. Hauri


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
like image 38
choroba Avatar answered Jan 28 '26 11:01

choroba