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?