How to have bash script answer interactive prompts (no y/n only)?

时间:2017-04-09 23:57:03

标签: linux bash shell docker environment-variables

I am trying to build a Docker image from a tool called PHPCI. I was able to do almost everything but my first problem appears when I need to run a setup script for create database, setup usernames/password and do some kind of default configuration for the tool itself.

The script should be called as (see here - Installing from Composer):

php ./console phpci:install

And it'll start asking for some questions. This is a full example of what is being asked:

******************
 Welcome to PHPCI
******************

Checking requirements... OK

Please answer the following questions:
-------------------------------------

Please enter your MySQL host [localhost]: 
Please enter your MySQL database name [phpci]:
Please enter your MySQL username [phpci]: 
Please enter your MySQL password:   
Your PHPCI URL ("http://phpci.local" for example): http://phpci.localdomain
Use beanstalkd to manage build queue? <yes|no>
Skipping beanstalkd configuration.
Setting up your database... OK
Admin Email: <email>
Admin Name: <user_name>
Admin Password:
User account created!

I am storing most of those parameters in ENV variables so I can read them easily after the container start. Or even better they can be ARG. My question is how I can make the install script to read the values from the ENV variables?

I know there is a lot of answers out there but most of them are for yes|no questions which seems to be easy but I couldn't find anything helpful regarding this one. Any help is more than welcome.

1 个答案:

答案 0 :(得分:2)

考虑这两个测试脚本:

tmp()
{
  var=fred
  tmp2 << EOD
$var
EOD
}

tmp2 ()
{
  read var2
  echo $var2
}

如果你将它们粘贴到一个shell中,然后运行tmp,你就会得到这个:

> tmp
fred

“heredoc”语法允许您在程序后包含对脚本中提示的响应。所以你想要做的是

php ./console phpci:install <<EOD
$HOST
$DATABASE
$USERNAME
$PASSWORD
[ ... etc ... ]
EOD

那应该为你做。请注意,您也可以包含硬编码值(而不是变量)。

如果您愿意,可以阅读有关heredoc at Wikipedia的更多信息。

希望这有帮助!

相关问题