Bash Case 菜单 - 动态选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1712918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:23:29  来源:igfitidea点击:

Bash Case menu - dynamic choices

bashmenucase

提问by Chasester

I'm not sure what the policy is here on asking followup questions. So please excuse me if i'm breaking protocol. Earlier I was constructing a menu in bash ( Here)

我不确定这里关于询问后续问题的政策是什么。如果我违反了协议,请原谅。早些时候我在 bash 中构建了一个菜单(这里

And so far I've got it working really good. Code here.

到目前为止,我已经让它工作得非常好。代码在这里。

while [[ 1 ]]
do
    cat -n "$dumpfile"
    read -p "Please make a selection, select q to quit: " choice
    case $choice in
            # Check for digits
    [0-9] )   dtvariable=$(sed -n "$choice"p "$dumpfile")
              $dtvariable            ;;
     q|Q)
         break
           ;;
      *)
           echo "Invalid choice"
           ;;
    esac
done

Except - that works great for menu items up to 9. The menu will be dynamic - could have 1 item, 20 items, or 197 items. I've tried changing [0-9] to be [0-9][0-9] to see if it would take 12. But it doesn't. Can anyone put me on the right path? I suppose I could just remove the [0-9] part and take anything that is not q. But wouldn't it be better to look for numbers?

除了 - 这对于最多 9 个菜单项非常有用。菜单将是动态的 - 可以有 1 个项目、20 个项目或 197 个项目。我已经尝试将 [0-9] 更改为 [0-9][0-9] 以查看是否需要 12。但事实并非如此。谁能让我走上正确的道路?我想我可以删除 [0-9] 部分并取任何不是 q 的东西。但是寻找数字不是更好吗?

Thank you in advance.

先感谢您。

采纳答案by Paused until further notice.

I would do some validation on $choice:

我会做一些验证$choice

case $choice in
     # Check for digits
    +([0-9]))
        lines=($(wc -l ))
        if (( choice > 0 && choice <= lines ))
        then
            dtvariable=$(sed -n "$choice"p "$dumpfile")
            $dtvariable            ;;
        fi
# etc.

回答by Jim Garrison

Here's what I got to work. The primary differences are the addition of shopt -s extglob, which turns on extended pattern matching, and the +([0-9])pattern, which is the bash equivalent of regular expression [0-9]+

这就是我的工作。主要区别是添加了shopt -s extglob,它打开扩展模式匹配,以及+([0-9])模式,它是正则表达式的 bash 等价物[0-9]+

shopt -s extglob
while [[ 1 ]]
do
    read -p "Please make a selection, select q to quit: " choice
    case $choice in
            # Check for digits
    +([0-9]))  
         echo $choice ;;
     q|Q)
         break
           ;;
      *)
           echo "Invalid choice"
           ;;
    esac
done