how to use one validation function many times "bash centos"
I want to use only one validation function many times. I tried to make a validation function like beneath. How can I fix my code and use the validation function like this one many times?
#!/bin/bash
digit='^[[:digit:]]+$';
function numberValidate {
if [[ $1 =~ $digit ]];
then
echo "$1 is number. Correct";
else
echo “Enter only numbers”;
numberValidate
fi
}
printf “Enter the number 1 ”; read n1;
numberValidate $n1
printf “Enter the number 2”; read n2;
numberValidate $n2
Thanks.
Don't use recursion when a loop will do:
inputNumber () {
local digit='^[[:digit:]]+$'
read $n
until [[ ${!n} =~ $digit ]]; do
echo "Enter only numbers"
read $n
done
}
printf "Enter the number 1 "; inputNumber n1
printf "Enter the number 2 "; inputNumber n2
The preceding moves all the input into the validation function, and takes advantage of the fact that variables set in a function are global by default. The argument to inputNumber
is the name of the variable to set.
inputNumber () {
local digit='^[[:digit:]]+$'
outputvar=$1
shift
if [[ $# = 0 ]]; then
read -p "Please enter a number for ${outputvar} "
else
read -p "$* " n
fi
until [[ "${n}" =~ $digit ]]; do
read -p "Enter only numbers " n
done
printf -v "${outputvar}" '%s' "$n"
}
inputNumber n1 "Enter the number 1"
inputNumber n2 "Enter the number 2"
inputNumber n3
echo "n1=${n1} n2=${n2} n3=${n3}"
Question in a comment: How to reuse these? When you like functions like this one, you can collect them in files and put them in a dedicated directory. Perhaps choose ${HOME}/shlib as a folder and create files like iofunctions, datefunctions, dbfunctions and webfunctions (or io.sh, date.sh, db.sh and web.sh). Next you can source
the files with a dot:
$ head -2 ${HOME}/shlib/iofunctions
# This file should be included with ". path/iofunctions"
function inputnumber {
$ cat ${HOME}/bin/roger.sh
#!/bin/bash
# Some settings
shlibpath=/home/roger/shlib
# Include utilities
. "${shlibpath}"/iofunctions
# Let's rock
inputNumber rockcount How many rocks
# call an imaginary function that only accepts y and n
inputyn letsdoit Are you sure
You can put the functions (or source the function files) in your .profile/.bashrc, but that will give problems when you want to start the script in crontab (and you will get used to the functions and forget that inputNumber is not a standard bash function).
Another question is how you can refer to another directory that is on the same level as your script file (not a fixed path). Including ../shlib/iofunctions
will fail when you start your script using a path (like bin/roger.sh
). A good question with many answers, I can't tell which is the best:
How to set current working directory to the directory of the script?
Getting the source directory of a Bash script from within
Reliable way for a bash script to get the full path to itself?
How to set current working directory to the directory of the script?
how to get script directory in POSIX sh?