简体   繁体   English

这个Bash脚本菜单有什么问题?

[英]What is wrong with this Bash script menu?

I'm tired of typing in long commands to do simple things so I've written this short Bash menu script to speed things up: 我已经厌倦了输入长命令来执行简单的操作,因此我编写了这个简短的Bash菜单脚本来加快操作速度:

#!/usr/bin/env bash
PS3="Nginx? "
options=("start", "stop", "status", "exit")
select opt in "${options[@]}"
do
    case $opt in
        "start")
            sudo service nginx start
            ;;
        "stop")
            sudo service nginx stop
            ;;
        "status")
            sudo service nginx status
            ;;
        "exit")
            echo "Exiting"
            exit 1
            ;;
          *) echo "Invalid selection";;
     esac
done

It's displaying the menu correctly: 它正确显示菜单:

1) start
2) stop
3) status
4) exit

But only option 4, exit, works correctly. 但是只有选项4退出才能正常工作。 When I hit 1, 2, or 3, I get "Invalid selection". 当我按下1、2或3时,我得到“无效选择”。 Am I entering the sudo commands incorrectly? 我是否错误地输入了sudo命令? Thank you. 谢谢。

The actual menu displayed by this code is not what you gave in the question, but instead: 此代码显示的实际菜单不是您在问题中提供的菜单,而是:

1) start,
2) stop,
3) status,
4) exit

This difference -- commas on the end of the first three items -- is instructive. 前三个项目末尾的逗号之间的区别很有启发性。


This is an array-syntax declaration issue. 这是一个数组语法声明问题。 Take out the commas: 取出逗号:

options=( "start" "stop" "status" "exit" )

...by the way, since your contents are all single-word literals with no glob characters, the quotes don't do anything; ...顺便说一句,由于您的内容都是单字面量的文字,没有glob字符,引号没有任何作用; it would be just as correct to write: 这样写是一样正确的:

options=( start stop status exit )

The original code accepts not start but start, ; 原始代码接受的不是start而是start, not stop , but stop, . 不是stop ,而是stop,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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