Simulating ENTER keypress in bash script

BashShellUbuntu

Bash Problem Overview


I've created a really simple bash script that runs a few commands. one of these commands needs user input during runtime. i.e it asks the user "do you want to blah blah blah?", I want to simply send an enter keypress to this so that the script will be completely automated.

I won't have to wait for the input or anything during runtime, its enough to just send the keypress and the input buffer will handle the rest.

Bash Solutions


Solution 1 - Bash

echo -ne '\n' | <yourfinecommandhere>

or taking advantage of the implicit newline that echo generates (thanks Marcin)

echo | <yourfinecommandhere>

Now we can simply use the --sk option:

> --sk, --skip-keypress Don't wait for a keypress after each test

i.e. sudo rkhunter --sk --checkall

Solution 2 - Bash

You might find the yes command useful.

See man yes

Solution 3 - Bash

You can just use yes.

# yes "" | someCommand

Solution 4 - Bash

Here is sample usage using expect:

#!/usr/bin/expect
set timeout 360
spawn my_command # Replace with your command.
expect "Do you want to continue?" { send "\r" }

Check: man expect for further information.

Solution 5 - Bash

You could make use of expect (man expect comes with examples).

Solution 6 - Bash

I know this is old but hopefully, someone will find this helpful.

If you have multiple user inputs that need to be handled you can use process substitution and use echo as a 'file' for cat with whatever is needed to handle the first input like this:

# cat ignores stdin if it has a file to look at
cat <(echo "selection here") | command

and then you can handle subsequent inputs by piping the yes command with the answer:

 cat <(echo "selection here") | yes 'y' | command

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontobbrView Question on Stackoverflow
Solution 1 - BashTilman VogelView Answer on Stackoverflow
Solution 2 - BashpaviumView Answer on Stackoverflow
Solution 3 - BashDavid HamnerView Answer on Stackoverflow
Solution 4 - BashkenorbView Answer on Stackoverflow
Solution 5 - Bashbarti_dduView Answer on Stackoverflow
Solution 6 - BashBocar View Answer on Stackoverflow