简体   繁体   中英

dynamically providing default input to calling script from a shell script

I have a shell-script main_script.sh, which will in term call 3 other scripts (a1.sh,a2.sh,a3.sh). Now on execution of a1.sh/a2.sh/a3.sh I need to answer some verbose with Y/N.

I know that each of a1.sh/a2.sh/a3.sh will need 2 Y/N.

How can I implement main_script.sh,so I don't have to answer Y/N requests while execution?

It depends on how the scripts are written. You mentioned each script needing two Y . I presume that each Y will need to be followed by an enter key (newline). In this case, it could be as simple as using the following for main_script.sh :

#!/bin/bash
echo $'Y\nY\n' | bash a1.sh
echo $'Y\nY\n' | bash a2.sh
echo $'Y\nY\n' | bash a3.sh

Above, the echo command sends two Y and newline characters to each of the scripts. You can adjust this as needed.

Some scripts will insist that interactive input come from the terminal, not stdin. Such scripts are harder, but not impossible, to fool. For them, use expect / pexpect .

More details

Let's look in more detail at one of those commands:

echo $'Y\nY\n' | bash a1.sh

The | is the pipe symbol. It connects the standard out of the echo command to the standard input of the a1.sh command. If a1.sh is amenable, this may allow us to pre-answer any and all questions that a1.sh asks.

In this case, the output from the echo command is $'Y\\nY\\n' . This is a bash shell syntax meaning Y , followed by newline character, denoted by \\n , followed by Y , followed by newline, \\n . A newline character is the same thing that the enter or return key generates.

Using expect

If your script does not accept input on stdin, then expect can be used to automate the interaction with script. As an example:

#!/bin/sh

expect <<EOF1
spawn a1.sh
expect "?"
send "Y\r"
expect "?"
send "Y\r"
sleep 1
EOF1

expect <<EOF2
spawn a2.sh
expect "?"
send "Y\r"
expect "?"
send "Y\r"
sleep 1
EOF2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM