在shell脚本中输入专有命令提示符

时间:2017-07-24 12:18:57

标签: bash shell sh user-input command-prompt

我想知道我们如何为更改命令提示提供输入。我想使用shell脚本

“#”通常提示和'>'的示例是特定于我的程序的提示:

mypc:/home/usr1#
mypc:/home/usr1# myprogram
myprompt> command1
response1
myprompt> command2
response2
myprompt> exit
mypc:/home/usr1#
mypc:/home/usr1# 

3 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望按顺序向程序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

要启动,只需调用myscript.expect,如果脚本与myprogram位于同一文件夹中。

答案 1 :(得分:0)

鉴于myprogram是一个脚本,它必须提示输入while read IT; do ...something with $IT ...;done之类的内容。很难确切地说如何更改该脚本而不看它。 echo -n 'myprompt>将是最简单的补充。

答案 2 :(得分:0)

可以使用PS3select构建

来完成
#!/bin/bash

PS3='myprompt> '

select cmd in command1 command2
do
    case $REPLY in
        command1)
            echo response1
            ;;
        command2)
            echo response2
            ;;
        exit)
            break
            ;;
    esac
done

echoread内置

prompt='myprompt> '
while [[ $cmd != exit ]]; do
    echo -n "$prompt"
    read cmd
    echo ${cmd/#command/response}
done