GT Wu GT Wu - 1 month ago 6x
Linux Question

Input string with format into a bash command

I would like to hard code some inputs to my bash script command. For example, I have a bash script like this:

#! /bin/bash
apt-get install python

and I would like to hard code
as the input for the
command in this bash script, as sometime user might b asked to confirm the space of the installation. I know I can do

apt-get install python <<< 'y'

to pass a string input
, but can I also input special format, like the newline '\n' using this method? Thanks!


All herestrings automatically are terminated by a newline, so this may not do what you want. (Many programs look at whether their input is coming from a TTY, and change whether and how they prompt based on the result; others read prompts intended to come from a user directly from a TTY, and so bypass piped contents, heredocs, and herestrings entirely).

That said, for a literal answer to the question:

apt-get install python <<<$'y\n'

You can also use a heredoc:

apt-get install python <<EOF


That said, for the specific case of apt-get, don't do that!

apt-get install -y python indeed the best practice. (And for system administration commands in general, batch or automated use is generally anticipated by their developers, so end-user input is rarely required -- look in each program's documentation for arguments such as --batch, --force, --always or --yes; environment variables that specify items that otherwise would be prompted for; or behaviors activated by having stdin not be a TTY).