Prateek Naik
Prateek Naik

Reputation: 2792

Need to simulate series of keyboard key events in shell script

Since i am beginner in shell scripting and don't know much about the simulating keyboard keys in scripting.

In one of my script i need to run, bq init after this it asks series of questions which involves keyboard events like pressing yes/no after pressing yes again it asks yes or no then it asks to enter the number like 1 or 2.

I can manage pressing 1st keyboard key event just by running echo "y" | big init but for later questions/keys i am clueless. can anyone help with this....

Upvotes: 0

Views: 446

Answers (3)

Mark Setchell
Mark Setchell

Reputation: 207405

There are lots of ways to do this. This way may seem intuitive (a "heredoc"):

yourScript << EOF
bq init
yes
no
maybe
1
2
EOF

Or this may appeal to you (a "compound statement"):

{ echo "yes"; echo "no"; echo "maybe"; echo "1"; } | yourScript

Or, the same spelled out line by line:

{ 
   echo "yes"
   echo "no"
   echo "maybe"
   echo "1"
} | yourScript

Or like this with printf:

printf "%s\n" "yes" "no" "maybe" "1" | yourScript

Upvotes: 1

zeppelin
zeppelin

Reputation: 9355

A right tool for the job like that is expect

Expect is a program that "talks" to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be.

Your script might look something like that:

#!/usr/bin/expect

spawn "./myscript.sh"

expect "First question ?" 
send "y\r"

expect "Second question ?"
send "2\r"

interact

This will spawn "myscript.sh", wait for it to ask the "First question ?" and reply with "y", then wait for the "Second question ?" and reply with "2".

Upvotes: 0

Mohan Rex
Mohan Rex

Reputation: 1674

You can pipe your input to the program.

your_program <<< $'yes\nno\nyour_name\n'

You can read more from here

Upvotes: 0

Related Questions