交互式 shell 脚本框架 (bash)

itj*_*itj 1 linux script shell shell-script

我当前的项目在 linux 机器上运行一个测试系统(有 9 个活动屏幕)

整个团队都熟悉如何开始测试等。但不太熟悉用于检查进度、移动文件、强制停止测试等的命令。

我想编写一个脚本,可以将有用的检查放在一起,通过一个简单的按键来踢它们。我可以很容易地在 Perl 中做到这一点,但如果它是一个 shell 脚本 (bash),则更一致。

虽然我的 shell 经验有限,但我想要一个易于其他人扩展的示例脚本(即框架)。

Wait for Key
Perform action
  Possibly accept further input for action
Repeat
Run Code Online (Sandbox Code Playgroud)

如果没有收到密钥,则每 n 分钟运行一次操作。

Dav*_*d Z 6

根据您的描述,这里有一些简单的事情(感谢丹尼斯的评论):

while true; do
    # 300 is the time interval in seconds
    if read -n 1 -t 300; then
        case $REPLY in
        a)
            # command(s) to be run if the 'a' key is pressed
            echo a;;
        b)
            # command(s) to be run if the 'b' key is pressed
            echo b;;
        esac
    else
        # command(s) to be run if nothing is pressed after a certain time interval
        echo
    fi
done
Run Code Online (Sandbox Code Playgroud)

这是我之前的替代方案,虽然我不记得我case最初为什么决定反对:

# define functions here
a_pressed() {
    # command(s) to be run if the 'a' key is pressed
}

b_pressed() {
    # commands for if 'b' is pressed
}

# etc.

nothing_pressed() {
    # command(s) to be run if nothing is pressed after a certain time interval
}

while true; do
    # 300 is the time interval in seconds
    if read -n 1 -t 300; then
        fn_name="${REPLY}_pressed"
        declare -pF | grep -q "$fn_name" && ${fn_name}
    else
        nothing_pressed
    fi
done
Run Code Online (Sandbox Code Playgroud)

无论哪种方式,这都将处理按键操作,并会在 5 分钟内没有任何操作时自动调用操作。