Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate key press in bash

Tags:

bash

I have a question, Im having very simple script that starts anpther binary file in loop it looka like this:

for (( i=0; \\$i <= 5; i++ )) ; do 
 test.sh 
done

Now problem is that after each execution test.sh asks me if I want to to override log something Like "Do you want to override log? [Y/n]"

After that prompt appears scripts pauses and iteration is stopped until I manually press Y and that it continues until another prompt appears.

To automate process can I simulate pressing "Y" button?

like image 920
Wojciech Szabowicz Avatar asked Dec 23 '22 22:12

Wojciech Szabowicz


2 Answers

I believe using yes might be enough if your test.sh script doesn't use its standard input for other purposes : yes will produce an infinite stream of lines of y by default, or any other string you pass it as a parameter. Each time the test.sh checks for user input, it should consume a line of that input and carry on with its actions.

Using yes Y, you could provide your test.sh script with more Y than it will ever need :

yes Y | test.sh

To use it with your loop, you might as well pipe it to the loop's stdin rather than to the test.sh invocation :

yes Y | for (( i=0; i <= 5; i++ )) ; do 
 test.sh 
done
like image 77
Aaron Avatar answered Jan 10 '23 04:01

Aaron


Something like the following code snippet should work :

for (( i=0; i <= 5; i++ ))
#heredoc. the '-' is needed to take tabulations into acount (for readability sake)
#we begin our expect bloc
do /bin/usr/expect <<-EOD
    #process we monitor
    spawn test.sh
    #when the monitored process displays the string "[Y/n]" ...
    expect "[Y/n]"
    #... we send it the string "y" followed by the enter key ("\r") 
    send "y\r"
#we exit our expect block
EOD
done
like image 36
Aserre Avatar answered Jan 10 '23 03:01

Aserre