I need your help in identifying my problem below,
My intention is to loop the input of the values while at the same time checking the input value if its [0-9] then saves it to a file then sorts the output of it.
My problem is that, whenever i run the script, the values retained as 1 2 3 4 5 not the one that i have inputted, can you help me on this ? i think there is a problem in my variable declaration in the conditional statements, but i dont know any workaround on it.
#!/bin/bash -x
echo > save.txt
validnum='0-9'
for ((i=1;i<=5;i++))
do
read -p "Please enter number $i: " num_$i
if [[ ! $num_$i =~ [^$validnum$] ]] && [[ $num_$i == "" ]]
then
echo "Input numbers have been validated.."
echo $num_$i >> save.txt
else
echo "INVALID CHARACTERS IDENTIFIED.."
echo "Please review your Input Values"
exit 0
fi
done
echo "Sorting values.."
echo "Below are the sorted values"
echo `cat save.txt | sort -n`
here is the expanded version whenever i ran the script.
+ echo
+ validnum=0-9
+ (( i=1 ))
+ (( i<=5 ))
+ read -p 'Please enter number 1: ' num_1
Please enter number 1:
+ [[ ! 1 =~ [^0-9$] ]]
+ [[ ! 1 == '' ]]
+ echo 'Input numbers have been validated..'
Input numbers have been validated..
+ echo 1
+ (( i++ ))
+ (( i<=5 ))
+ read -p 'Please enter number 2: ' num_2
Please enter number 2:
+ [[ ! 2 =~ [^0-9$] ]]
+ [[ ! 2 == '' ]]
+ echo 'Input numbers have been validated..'
Input numbers have been validated..
+ echo 2
+ (( i++ ))
+ (( i<=5 ))
+ read -p 'Please enter number 3: ' num_3
Please enter number 3:
+ [[ ! 3 =~ [^0-9$] ]]
+ [[ ! 3 == '' ]]
+ echo 'Input numbers have been validated..'
Input numbers have been validated..
+ echo 3
+ (( i++ ))
+ (( i<=5 ))
+ read -p 'Please enter number 4: ' num_4
Please enter number 4:
+ [[ ! 4 =~ [^0-9$] ]]
+ [[ ! 4 == '' ]]
+ echo 'Input numbers have been validated..'
Input numbers have been validated..
+ echo 4
+ (( i++ ))
+ (( i<=5 ))
+ read -p 'Please enter number 5: ' num_5
Please enter number 5:
+ [[ ! 5 =~ [^0-9$] ]]
+ [[ ! 5 == '' ]]
+ echo 'Input numbers have been validated..'
Input numbers have been validated..
+ echo 5
+ (( i++ ))
+ (( i<=5 ))
+ echo 'Sorting values..'
Sorting values..
+ echo 'Below are the sorted values'
Below are the sorted values
++ cat save.txt
++ sort -n
+ echo 1 2 3 4 5
1 2 3 4 5
num_$i. Probably best to use an arraytmp=num_$i; if [[ ! ${!tmp} =~ ^$validnum$ ]] && [[ ${!tmp} == "" ]]. Better to recognize that you don't need separate variables for each iteration of the loop.[[ ! $num_$i =~ [^$validnum$] ]]can't work? Because$num_$iis expanded two variablesnum_andi. Because the namenum_is a valid variable name in Bash. So it will parse they are two variables. But if you enclosed it with brackets like${num_$i}will not work. Because it will complainbad substitutionerror. If you want it work, you can use Indirect References.var="num_$i" ; echo ${!var}will work. Please refer to Bash dynamic variable names.