Stephanie
Stephanie

Reputation: 9

How can my bash script repeat a prompt until it gets a valid value?

I'm making a bash program that lets a user write a number between 1 and 10 and then proceeds to create the same amount of directories the user typed. Is there a way I can make my program keep asking the question if the user didn't write a number between 1 or 10 instead of having it close? Also, is there any way I can validate the input so that the program won't crash if the user writes a letter instead of a number? Any help or tips would be greatly appreciated.

#!/bin/bash
read -p "How many directories would you like?" num_folder
if test $num_folder -lt 10
then
    for ((i=0; i<num_folder; i++)); do
      mkdir folder$i        
    done



    read -rsp "Press enter to continue"
    clear

else
    echo "Please write a number between 1 and 10"      
fi

Upvotes: 0

Views: 1031

Answers (2)

user4918296
user4918296

Reputation:

You could wrap the read instruction in a loop:

is_integer() {
    [[ "$1" =~ ^[[:digit:]]+$ ]]
}

while ! is_integer "$num_folder";do
    read -p "How many directories would you like?" num_folder
done

...

The function is_integer checks if the passed value is a valid integer.

Upvotes: 2

Stephen P
Stephen P

Reputation: 14800

Just to expand on @nautical's answer a little -- this version ensures the number entered is between one and ten, and will take a command line parameter.
If the parameter is acceptable (numeric, from one to ten) it doesn't prompt.

#!/bin/bash

is_integer() {
    [[ "$1" =~ ^[[:digit:]]+$ && $1 -gt 0 && $1 -le 10 ]]
}

num_folder=${1}

while ! is_integer "$num_folder";do
    read -p 'How many directories would you like [1-10]? ' num_folder
done

echo "num_folder is $num_folder"
# continue with your actual code to make the directories

Upvotes: 0

Related Questions