Passing arguments to an interactive program non-interactively

痞子三分冷 提交于 2019-12-16 19:58:11

问题


I have a bash script that employs the read command to read arguments to commands interactively, for example yes/no options. Is there a way to call this script in a non-interactive script passing default option values as arguments?

It's not just one option that I have to pass to the interactive script.


回答1:


For more complex tasks there is expect ( http://en.wikipedia.org/wiki/Expect ). It basically simulates a user, you can code a script how to react to specific program outputs and related stuff.

This also works in cases like ssh that prohibits piping passwords to it.




回答2:


Many ways

pipe your input

echo "yes
no
maybe" | your_program

redirect from a file

your_program < answers.txt

use a here document (this can be very readable)

your_program << ANSWERS
yes
no
maybe
ANSWERS

use a here string

your_program <<< $'yes\nno\nmaybe\n'



回答3:


You can put the data in a file and re-direct it like this:

$ cat file.sh
#!/bin/bash

read x
read y
echo $x
echo $y

Data for the script:

$ cat data.txt
2
3

Executing the script:

$ file.sh < data.txt
2
3



回答4:


Just want to add one more way. Found it elsewhere, and is quite simple. Say I want to pass yes for all the prompts at command line for a command "execute_command", Then I would simply pipe yes to it.

yes | execute_command

This will use yes as the answer to all yes/no prompts.



来源:https://stackoverflow.com/questions/14392525/passing-arguments-to-an-interactive-program-non-interactively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!