lundi 3 mai 2021

Shell Scripting - Numeric Checks and if statement questions

I'm relatively new here and to the coding world. I'm currently taking a class in Shell Scripting and I'm a bit stuck.

I'm trying to do a little extra credit and get the script to check for command line arguments and if none or only 1 is given, prompt the user to input the missing values.

For the most part I've been able to get most of it to work except for when it comes to the numeric check part. I'm not completely sure that I am doing the nested if statements correctly because it's displaying both the "if" echo and the "else" echo.

My script so far:

q=y
# Begins loop
until [[ $q == n ]];do
    # Checks command line arguments
    if [[ $# -lt 2 ]];then
        # Asks for second number if only 1 argument.
        if [[ $# == 1 ]];then
            read -r -p "Please enter your second number: " y
            if [[ y =~ [1-9] ]];then
                echo "You've chosen $1 as your first number and $y as your second number."
                break
            else
                echo "This is not a valid value, please try again."
            fi
        # Asks for both numbers if no arguments.
        else
            read -r -p "Please enter your first number: " x
            if [[ x =~ [1-9] ]];then
                break
            else
                echo "This is not a valid value, please try again."
            fi
            read -r -p "Please enter your second number: " y
            if [[ y =~ [1-9] ]];then
                break
            else
                echo "This is not a valid value, please try again."
            fi
        echo "You've chosen $x as your first number and $y as your second number."
        fi
    # If both command line arguments are provided, echo's arguments, and sets arguments as x and y values.
    else
        echo "You've chosen $1 as your first number and $2 as your second number."
        x=$1
        y=$2
    fi
    read -r -p "Would you like to try again? (n to exit): " q
done

When I run it I get this for output:

Please enter your first number: 1
This is not a valid value, please try again.
Please enter your second number: 2
This is not a valid value, please try again.
You've chosen 1 as your first number and 2 as your second number.
Please enter your first number: 

And will just continue to loop without breaking. Any help/guidance would be greatly appreciated, thank you.

Aucun commentaire:

Enregistrer un commentaire