I need a bash script to select 2 random nameservers from a list. This is what I have that is not working - I get an error on the line "$(($RANDOM % ${SIZE}))" and I can't figure out why.
NAMESERVERS="x.x.x.x x.x.x.x x.x.x.x x.x.x.x"
SIZE=${#NAMESERVERS[@]}
# select 2 random entries
NS_IDX=$(($RANDOM % ${SIZE}))
NS_IDX2=${NS_IDX1}
while [ "${NS_IDX1}" == "${NS_IDX2}" ]
do
NS_IDX2=$(($RANDOM % ${IDX_RANGE}))
done
NS_IP1=${NAMESERVERS[${NX_IDX1}]}
NS_IP2=${NAMESERVERS[${NX_IDX2}]}
Then I echo NS_IP1 and NS_IP2 to /etc/resolv.conf
NS_IDX=$(($RANDOM % ${SIZE}))is ok,$SIZEhas a value and it isn't zero, but in the lineNS_IDX2=$(($RANDOM % ${IDX_RANGE})),$IDX_RANGEis null, this gives an error (maybe it has a value at that point). If you wantNAMESERVERSas an array, declare it asNAMESERVERS=(x.x.x.x x.x.x.x x.x.x.x x.x.x.x). Thewhilecommand is missing a closing], maybe a typo? – Paulo Aug 08 '23 at 14:00${NX_IDX1}and${NX_IDX2}are only used on the last two lines of your script? – Luuk Aug 08 '23 at 14:23For the error, the message is "7: arithmetic expression: expecting primary: "%81[@]"
I wonder if part of the problem is that the IP addresses are not being interpreted as IPs, but one character at a time.
Yes, i echo those ip's out to /etc/resolv.conf. I could echo them out using "${NAMESERVERS[${NS_IDX1}]} "
– kathyl Aug 08 '23 at 14:32$RANDOMthen you need a shell that supports it. A proper shebang is advised, e.g.#!/bin/bash -. Unless you are sourcing the script in Bash in order to use the variables after the script finishes; if so, then the lack of shebang is fine. – Kamil Maciorowski Aug 08 '23 at 17:28shcommand? If so, that overrides the shebang and runs it in plain sh, which probably doesn't have$RANDOM. Also, the assignment toNAMESERVERSis not creating an array, just a plain string with spaces; useNAMESERVERS=(x.x.x.x x.x.x.x x.x.x.x x.x.x.x)instead (the parentheses are what tells bash to make an array). I'd also recommend running your script through shellcheck.net as a sanity-check. Finally, it's safest to use lower- or mixed-case variable names, to avoid conflicts with the many special all-caps vars. – Gordon Davisson Aug 09 '23 at 19:23