Hello,
basically what this script is supposed to do is showing a list of hosts that is given a number, that you will be able to choose from a list.
A check is made to verify that the chosen number is within the array and this is where things go bad and I don't know why, bizarre.
I've spent quite some time trying to figure out why this function doesn't give the correct output (see below the script).
HOSTLIST="test1 test2 test3"
List_Hosts ()
{
num=1
hosts=
HI_HOSTS=
hostlist=(NULL $( echo $HOSTLIST ))
hostnumbers=${#hostlist[@]}
for (( i=1; i<${hostnumbers}; i++ )); do
hosts=$( echo "$hosts($num)-${hostlist[$i]} " )
let num=num+1
done
echo -e "\n$hosts\n"
echo -n "Enter number(s) (comma-separated - 1,2,3): "
read input
if [ -n "$( echo "$input" | tr , " " | tr -d '[0-9]' | awk '{print $1}' )" ]; then
echo -e "\nNone numerical value \"$input\" entered, please try again."
List_Hosts
else
for hostnum in $( echo "$input" | tr , " " ) ; do
if [ "$hostnum" -eq 0 -o "$hostnum" -gt $[$hostnumbers-1] ]; then
echo "Number \"$hostnum\" doesn't match existing values, please try again."
List_Hosts
fi
HI_HOSTS=$( echo "$HI_HOSTS${hostlist[$hostnum]} " )
done
fi
}
List_Hosts
echo $HI_HOSTS
output
# ./script.sh
(1)-test1 (2)-test2 (3)-test3
Enter number(s) (comma-separated - 1,2,3): 4
Number "4" doesn't match existing values, please try again.
(1)-test1 (2)-test2 (3)-test3
Enter number(s) (comma-separated - 1,2,3): 5
Number "5" doesn't match existing values, please try again.
(1)-test1 (2)-test2 (3)-test3
Enter number(s) (comma-separated - 1,2,3): 1,2
test1 test2 test2 test2
for each unmatched number it will add the last entry again. Running it without typing an unmatched number it will give the correct output.