Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value from pattern - bash

Tags:

bash

loops

I need to get value from <2018-2099>, if user will type wrong value then script will tell him that value is incorrect and will ask him to type again.

I already have something like this but it doesn't work.. Any suggestions?

#!/bin/bash

read -r -p "Type year [value from 2019-2099]" year
if [[ "$year" =~ ^(20[1-9]|[1-9])+$ ]]; then
    mkdir -p "/home/$year/"
else
    echo "$year - value is not correct. Try again." >&2 && exit 1
fi
like image 748
Marcin A Avatar asked Aug 11 '26 18:08

Marcin A


1 Answers

You can use function and until loop to achieve this, consider following code:

readYear() {
    read -r -p "Type year [value from 2018-2099]" year
    [[ "${year}" =~ ^[0-9]{4}$ ]] && [[ "${year}" -ge 2018 ]] && [[ "${year}" -le 2099 ]]
}

until readYear; do
    echo "${year} - value is not correct. Try again." >&2
done

The function returns 0 if the value entered is valid, then the loop terminates.

like image 126
tomix86 Avatar answered Aug 13 '26 07:08

tomix86