Error? bash select-- entered data is returned as an "unbound variable"

I am running Linux 3.10.0-693.2.2.el7.x86_64, and for life it is impossible for me to understand why this will happen. It seems to be a bug and the shellchecker does not detect any problems.

#!/bin/bash
set -o nounset

### functions
options=(one two three)

select var in "${options[@]}"; do
    # make sure it is a valid choice
    if (( REPLY <= ${#options[@]} )) && [[ $REPLY  =~ ^[0-9]+$ ]]; then
        case $var in
            one)   exit;;
            two)  df -h /tmp;;
            *)      echo $var;;
        esac
        break
    else
        printf "Invalid selection.\n" >&2
    fi

I used set -xv to troubleshoot, but here's the exit without it. During production, the options [@] will be set by the command, and the number they return will be dynamic. So I want the menu to execute the command in *) in $ var--, but I have to check the selection outside of limits in REPLY. Here is the result.

$ bad_select.bash
1) one
2) two
3) three
#? 4
Invalid selection.
#? t
/home/lc5550358/bin/select_menu.wip: line 9: t: unbound variable

twhich I typed? I can also avoid an unbound variable, but type in k=2or var(the latter is defined in select). Why and what is happening around (required set -o nounset)?

+4
1

bash . , (( REPLY <= ${#options[@]} )) REPLY. REPLY t, t , .

:

$ t=2*3; REPLY=t; echo $(( REPLY + 2 ))
8
$ REPLY=t; t=a+b; a=6; b=c; c=10; echo $(( REPLY + 2 ))
18
$ unset t; REPLY=t; echo $(( REPLY + 2 ))
bash: t: unbound variable

jm666, , REPLY , , REPLY .

var REPLY:

#!/bin/bash
set -o nounset

### functions
options=(one two three)

select var in "${options[@]}"; do
    # make sure it is a valid choice
    if [ "$var" ]; then
        case "$var" in
            one)   exit;;
            two)  df -h /tmp;;
            *)      echo "$var";;
        esac
        break
    else
        printf "Invalid selection.\n" >&2
    fi
done

, var , . var .

man bash :

; . , . 0 . , , , , declare -i, . 0. .

+4

Source: https://habr.com/ru/post/1690467/


All Articles