Search code examples
bashenterheredoc

Simulate ENTER key in bash here-document


Is there a way to simulate ENTER key in a bash script imputing values to a code through a here-document (EOF). Readily possible in bash, see question 6264596.

Pseudo code:

 #!/bin/bash
 code_executable << EOF
 value1
 value2 
 EOF

value2 needs to be followed by a carriage return, ie ENTER when executing from a shell.

Thanks guys.

Simulation of executable running on a terminal:

  $./code_executable
  >Do you want to continue? yes or no
  User: y
  >Enter number:
  User: 314 

If User doesn't press ENTER on keyboard after entering 314, executable hangs/halts there and waits.

Edit: see exceptions in stdin buffering that prevent the EOF from passing arguments to an executable as illustrated by @that other guy answer below.


Solution

  • * See that other guy's helpful answer for useful background information and tips for what the actual problem may be.
    * This answer assumes a well-behaved program that reads prompt inputs from stdin - as it turns out, not using such a program was precisely the OP's problem: their program behaves differently when inputs are provided via stdin as opposed to by interactive typing.

    Let's simulate your executable with the following script:

    #!/usr/bin/env bash
    
    printf ">Do you want to continue? (y)es or (n)o: "
    read -r -n 1  confirm  # NOTE: A *single* keypress terminates input here.
    printf "\nUser: $confirm\n"
    
    printf ">Enter number: "
    read -r  number
    printf "User: $number\n"
    

    To provide the sample input in your question to this script via stdin, using a here-document:

    ./code_executable <<EOF
    y314
    EOF
    

    Note the absence of a newline between y and 314 to account for the fact that the 1st prompt does not require an ENTER keypress to commit the input - only a single character.

    With a here-document, the overall input invariably ends in a newline (\n), which acts as if Enter had been pressed (as explained in that other guy's helpful answer) and therefore submits the input to the 2nd prompt.

    Additional prompt inputs can simply be added before the closing EOF delimiter, with each additional input that requires Enter to submit on its own line.

    ./code_executable <<EOF
    y314
    next input
    ...
    EOF