取消变量不起作用

时间:2016-11-09 17:56:01

标签: bash function unset

如果用户输入为整数,我想解析,并强制他这样做。第一次(iquant)正在运行chkip(),第二次(idays),我立即得到:"错误:不是数字。请重试。"然后新输入工作。我在ipn之前取消了break,那么这笔交易是什么?

chkip()
{
    ipn=$1
    while true;
    do
        if [[ "$ipn" =~ ^[0-9]+$ ]] ; then 
            unset ipn
            break
        else 
            echo "Error: Not a number. Please retry"
            read ipn
        fi
    done
}

echo "Please enter the name of the Set:"
read ap
echo "How much keys do you want to create [NUMBER]:"
read iquant
chkip $iquant 
echo "How often do you want to change the Keys? [DAYS] ?:"
read idays
chkip $idayz 

2 个答案:

答案 0 :(得分:3)

问题在于你正在阅读“iday s ”但是传递“iday z ”而不是前者。

read idays
chkip $idayz

$ idayz 更改为 $ idays ,您就可以了。

答案 1 :(得分:1)

你有一个更大的问题:你的函数只修改名为ipn的变量,而不是你作为参数传递的变量。

此函数获取变量的名称,并使用间接参数扩展来检查该变量的值。 var将作为要填充的变量的名称传递给read

chkip () {
  local var=$1
  until [[ ${!var} =~ ^[[:digit:]]$ ]]; then
    read -p "Error: Not a number. Please retry: " "$var"
  done
}

此处,变量的名称,而不是值,作为参数传递给chkip

read -p "Please enter the name of the set: " ap
read -p "How many keys do you want to create? [NUMBER]: " iquant
chkip iquant 
read -p "How often do you want to change the keys? [DAYS]: " idays
chkip idays