简体   繁体   English

如何在Linux中脱颖而出

[英]How to come out of select in Linux

I want to take the input from the user, which could be any of the given options, I tried using select , but it just goes in loop, doesn't come out, is there a way i can make it to come out and proceed after the user has entered right option, here is the sample code: 我想从用户那里得到输入,这可以是任何给定的选项,我尝试使用select ,但是它只是循环播放,没有出现,有没有办法让我显示出来并继续用户输入了正确的选项后,下面是示例代码:

select envir in "prod" "uat" "dev"; do
    echo $envir
done

//continue with the script
echo "out of select"

Once user selects any of the available options, it should come out and continue with the scripts, if the user has entered anything else, it should keep on prompting. 一旦用户选择了任何可用选项,它就会出现并继续执行脚本,如果用户输入了其他任何内容,则应继续提示。

select envir in "prod" "uat" "dev"; do
    echo $envir
    if [ $envir == "prod" ] || [ $envir == "uat" ] || [ $envir == "dev" ]
    then
        break
    fi
done

//continue with the script
echo "out of select"

From the bash(1) man page: 在bash(1)手册页中:

... The list is executed after each selection until a break command is executed. ...列表在每次选择后执行,直到执行中断命令为止。 The exit status of select is the exit status of the last command executed in list, or zero if no commands were exe- cuted. select的退出状态是列表中最后执行的命令的退出状态,如果未执行任何命令,则为零。 ... ...

In other words, execute a "break" statement when $envir is nonempty. 换句话说,当$ envir为非空时,执行“ break”语句。

I would write the above script this way: 我会这样写上面的脚本:

#!/bin/bash
declare -a opts=("prod" "uat" "dev")

echo "control-D to exit"
select envir in "${opts[@]}"; do
    echo "envir=$envir"
    found=0
    for elem in "${opts[@]}"; do
       if [ "$elem" = "$envir" ]; then
          found=1
          break
       fi
    done
    if [ "$found" -eq 1 ]; then
       break
    fi
done

echo "out of select"

That way your keywords are handled at one place. 这样一来,您的关键字就会在一个地方得到处理。 Every time you add a new word in the list of "prod" "uat" "dev", you don't need to change at 2 places. 每次在“ prod”,“ uat”,“ dev”列表中添加新单词时,都不需要在2个位置进行更改。

You can also read the list of words from an external file and assign that to bash array variable opts here. 您还可以从外部文件中读取单词列表,并将其分配给bash数组变量opts。

Thanks Brian. 谢谢布莱恩。 With your input, this is what I was able to do: 通过您的输入,这就是我能够做到的:

select envir in "prod" "uat" "dev"; do
    echo $envir
    if [ "$envir" != "" ]
    then
        break
    fi
done

//continue with the script
echo "out of select"

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

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