2

If I want to simulate an enter key pressed,I just use:

echo -ne '\n' | mycommand

But "mycommand" requires to wait some seconds before actually press enter key. How could I wait some seconds before simulate the enter key pressing?

3 Answers 3

4

Use expect, something like this should do:

#!/usr/bin/env expect
spawn "mycommand"
expect "Press Enter to continue" { send "\r" }
interact

Of course, you need to change "Press Enter to continue" to the actual message.

5
  • 1
    Instead of echo... with flags, which acts differently depending on shell, consider using the more well-defined printf "\n" (or plain echo I suppose) Commented Jul 16, 2020 at 15:07
  • Or echo alone which sends a newline by itself already. Feels silly to remove that newline with -n (non-standard) just to add it back with -e (even less portable) and \n. Commented Jul 16, 2020 at 15:07
  • I just took that from the Q. But as you already have the more or less the same answer i switched to an expect solution ;-)
    – pLumo
    Commented Jul 16, 2020 at 15:10
  • You may want to do send "\r" instead of send "\n" to similar pressing Return (shouldn't make much difference as the pty line discipline will likely translate \r to \n anyway) Commented Jul 16, 2020 at 15:11
  • 1
    (see also spawn -noecho to avoid echoing the command. Maybe #! /usr/bin/env expect as not many systems have expect in /bin. Commented Jul 16, 2020 at 15:14
2
(sleep 12; echo) | mycommand

mycommand will read an empty line after 12 seconds and see end-of-file straight after. If that's a problem, you can add a delay after as well:

(sleep 12; echo; sleep 5) | mycommand

See also expect to send input based on what the command outputs (it also uses pseudo-terminals which makes it look like there's a real user).

2
  • it works. but why mycommand executes before the end of commands in ()?
    – wsdzbm
    Commented Oct 13, 2022 at 9:39
  • 1
    @ddzzbbwwmm in a pipeline, all parts are started at the same time and run concurrently. Commented Nov 19, 2022 at 8:29
0

you could use xdotool to simulate a "enter":

 xdotool key 'Return' | commandhere

or you can make it sleep then enter a command:

sleep 0.5; xdotool key 'Return' | commandhere
3
  • I think the intention was that the target program would start running, but it would then receive {Enter} after a few moments. A bit like this other answer Commented Sep 3, 2023 at 19:03
  • @roaima that works with this script sleep 0.5; xdotool key 'Return' | curl repo.jellyfin.org/install-debuntu.sh | sudo bash in this example the script installs jellyfin and presses enter when prompted Commented Sep 4, 2023 at 0:53
  • Not really. It sends the Enter key immediately but the script downloaded from curl only looks for it after a few moments. That's different to the requirement Commented Sep 4, 2023 at 9:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .