Friday, April 26, 2024
386
rated 0 times [  386] [ 0]  / answers: 1 / hits: 580314  / 2 Years ago, thu, june 30, 2022, 3:35:00

I'm running a script that it requests entering 'y' on each operation, I am looking for a solution like $ ./script < echo 'yyyyyyyyyyyyyy' to pass all my inputs in one time.


More From » command-line

 Answers
3

There is a command created specifically for that case: yes


$ yes | ./script

What this does is connect the output of yes to the input of ./script. So when ./script asks for user input it will instead get the output of yes. The output of yes is an endless stream of y followed by enter. So basically as if the user is entering y for every question of ./script.


If you want to say no (n) instead of yes (y) you can do it like this:


$ yes n | ./script

Note that some tools have an option to always asume yes as answer. See here for example: Bypass the yes/no prompt in 'apt-get upgrade'




Other methods to enter input:


If you know exactly how many y your script is expecting you can do it like this:


$ printf 'y
y
y
' | ./script

The newlines (
) are the enter keys.


Using printf instead of yes you have more fine grained control of input:


$ printf 'yes
no
maybe
' | ./script

Note that in some rare cases the command does not require the user to press enter after the character. in that case leave the newlines out:


$ printf 'yyy' | ./script

For sake of completeness you can also use a here document:


$ ./script << EOF
y
y
y
EOF

Or if your shell supports it a here string:


$ ./script <<< "y
y
y
"

Or you can create a file with one input per line:


$ ./script < inputfile

If the command is sufficiently complex and the methods above no longer suffice then you can use expect.


Here is an example of a super simple expect script:


spawn ./script
expect "are you sure?"
send "yes
"
expect "are you really sure?"
send "YES!
"
expect eof



Technical nitpick:


The hypothetical command invocation you gave in your question does not work:


$ ./script < echo 'yyyyyyyyyyyyyy'
bash: echo: No such file or directory

This is because the shell grammar allows a redirect operator anywhere in the command line. As far as the shell is concerned your hypothetical command line is the same as this line:


$ ./script 'yyyyyyyyyyyyyy' < echo
bash: echo: No such file or directory

That means ./script will be called with the argument 'yyyyyyyyyyyyyy' and the stdin will get input from a file named echo. And bash complains since the file does not exists.


[#29708] Friday, July 1, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
uxuriousrnal

Total Points: 279
Total Questions: 106
Total Answers: 96

Location: Fiji
Member since Wed, Mar 29, 2023
1 Year ago
uxuriousrnal questions
Wed, Mar 9, 22, 09:04, 2 Years ago
Mon, Jul 18, 22, 01:48, 2 Years ago
Wed, Apr 13, 22, 01:15, 2 Years ago
Thu, Aug 26, 21, 22:01, 3 Years ago
;