在 shell 脚本中输入专有命令提示符
Input to proprietary command prompt in shell script
我想知道我们如何为发生变化的命令提示符提供输入。我想使用 shell 脚本
示例,其中“#”是常用提示符,“>”是特定于我的程序的提示符:
mypc:/home/usr1#
mypc:/home/usr1# myprogram
myprompt> command1
response1
myprompt> command2
response2
myprompt> exit
mypc:/home/usr1#
mypc:/home/usr1#
如果我没理解错的话,您想向程序myprogram
顺序发送特定命令。
为此,您可以使用一个简单的 expect
脚本。我假设 myprogram
的提示用 myprompt>
注释,并且 myprompt>
符号没有出现在 response1
中:
#!/usr/bin/expect -f
#this is the process we monitor
spawn ./myprogram
#we wait until 'myprompt>' is displayed on screen
expect "myprompt>" {
#when this appears, we send the following input (\r is the ENTER key press)
send "command1\r"
}
#we wait until the 1st command is executed and 'myprompt>' is displayed again
expect "myprompt>" {
#same steps as before
send "command2\r"
}
#if we want to manually interract with our program, uncomment the following line.
#otherwise, the program will terminate once 'command2' is executed
#interact
如果脚本与 myprogram
.
在同一文件夹中,只需调用 myscript.expect
即可启动
鉴于 myprogram
是一个脚本,它必须提示输入类似 while read IT; do ...something with $IT ...;done
的内容。很难确切地说出如何在没有看到它的情况下更改该脚本。 echo -n 'myprompt>
是最简单的加法。
可以用PS3
和select
构建
#!/bin/bash
PS3='myprompt> '
select cmd in command1 command2
do
case $REPLY in
command1)
echo response1
;;
command2)
echo response2
;;
exit)
break
;;
esac
done
或使用 echo
和 read
内置函数
prompt='myprompt> '
while [[ $cmd != exit ]]; do
echo -n "$prompt"
read cmd
echo ${cmd/#command/response}
done
我想知道我们如何为发生变化的命令提示符提供输入。我想使用 shell 脚本
示例,其中“#”是常用提示符,“>”是特定于我的程序的提示符:
mypc:/home/usr1#
mypc:/home/usr1# myprogram
myprompt> command1
response1
myprompt> command2
response2
myprompt> exit
mypc:/home/usr1#
mypc:/home/usr1#
如果我没理解错的话,您想向程序myprogram
顺序发送特定命令。
为此,您可以使用一个简单的 expect
脚本。我假设 myprogram
的提示用 myprompt>
注释,并且 myprompt>
符号没有出现在 response1
中:
#!/usr/bin/expect -f
#this is the process we monitor
spawn ./myprogram
#we wait until 'myprompt>' is displayed on screen
expect "myprompt>" {
#when this appears, we send the following input (\r is the ENTER key press)
send "command1\r"
}
#we wait until the 1st command is executed and 'myprompt>' is displayed again
expect "myprompt>" {
#same steps as before
send "command2\r"
}
#if we want to manually interract with our program, uncomment the following line.
#otherwise, the program will terminate once 'command2' is executed
#interact
如果脚本与 myprogram
.
myscript.expect
即可启动
鉴于 myprogram
是一个脚本,它必须提示输入类似 while read IT; do ...something with $IT ...;done
的内容。很难确切地说出如何在没有看到它的情况下更改该脚本。 echo -n 'myprompt>
是最简单的加法。
可以用PS3
和select
构建
#!/bin/bash
PS3='myprompt> '
select cmd in command1 command2
do
case $REPLY in
command1)
echo response1
;;
command2)
echo response2
;;
exit)
break
;;
esac
done
或使用 echo
和 read
内置函数
prompt='myprompt> '
while [[ $cmd != exit ]]; do
echo -n "$prompt"
read cmd
echo ${cmd/#command/response}
done