Bash: select statement doesn't break

旧巷老猫 提交于 2021-02-11 04:53:38

问题


Here's a function containing a select statement that doesn't break unless you choose 'quit':

function func_set_branch () {
        local _file=$1
        local _expr=$2
        local _bdate=$3
        local _edate=$4
        local _mid=$(awk -F'\t' -v ref="${_expr}" 'BEGIN {IGNORECASE = 1} match($0, ref) {print $5}' "$CONF")

        if (( $(grep -c . <<<"${_mid}") > 1 )); then
                mapfile -t arr <<< "${_mid}"

                PS3="Please choose an option "
                select option in "${arr[0]}" "${arr[1]}" quit
                do
                        case $option in
                                1) _mid="${arr[0]}"; break 2;;
                                2) _mid="${arr[1]}"; break 2;;
                                quit) exit 0;;
                        esac
                done
        fi

        sed "s#{{mid}}#${_mid}#
             s#{{bdate}}#${_bdate}#
             s#{{edate}}#${_edate}#" "$_file"
}

I've tried different levels of break ..no dice. What have I missed after staring at this waaaay tooo long?

Output:

automation@automation-workstation2:~/scripts/branch-fines$ bash get_data.sh -f branch-fines.sql -B coulee -b 2014-01-01 -e 2014-12-31
coulee 2014-01-01 to 2014-12-31
1) 472754
2) 472758
3) quit
Please choose an option 1
Please choose an option 2
Please choose an option 3
automation@automation-workstation2:~/scripts/branch-fines$

UPDATE

Working code with much thanks to rici and glenn jackman.

PS3="Please choose an option "
select option in "${arr[0]}" "${arr[1]}" quit
do
    case $option in
        "${arr[0]}") MID="${arr[0]}"; break;;
        "${arr[1]}") MID="${arr[1]}"; break;;
        quit) exit 0;;
    esac
done

回答1:


In the body of the select statement, the specified variable ($option in this case) is set to the value of the selected word, not its index. That's why quit works; you're checking to see if $option is quit, not 3. Similarly, you should be checking for ${arr[0]} and ${arr[1]} rather than 1 and 2.

Since the array values are not 1 or 2, no clause in the case statement will match, so the case statement will do nothing; in that case, no break is executed so the select continues looping.



来源:https://stackoverflow.com/questions/28226939/bash-select-statement-doesnt-break

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!