1

I want to parse if the user input is an integer, and force him to do so. First time (iquant) running chkip() works, second time (idays), I immediately get: "Error: Not a number. Please retry." New input works then. I am unsetting ipn before break, so what's the deal?

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 
3
  • You probably want to quote those expansions ("$1", "$iquant", etc), and consider set -u to get an error when you try to use an unset variable. Commented Nov 9, 2016 at 18:09
  • Maybe you should also add a return value, because after the correction iquant will contain the old value and ipn will be out of scope. Commented Nov 9, 2016 at 18:12
  • Welcome to stackoverflow! +1 for including complete, self-contained source code, expected result and actual result. This makes the question clear, unambiguous and easy to answer and verify. Commented Nov 9, 2016 at 19:24

2 Answers 2

3

The problem is that you're reading "idays" but passing "idayz" instead of the former.

read idays
chkip $idayz

Change $idayz to $idays and you'll be on your way.

Sign up to request clarification or add additional context in comments.

Comments

1

You have a bigger problem: your function only modifies the variable named ipn, not whatever variable whose value you pass as an argument.

This function takes the name of a variable, and uses indirect parameter expansion to check the value of that variable. The value of var is passed to read as the name of the variable to populate.

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

Here, the name, not the value, of the variable is passed as the argument to 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.