Vagho Vagho - 4 months ago 15
Bash Question

until item does not exists in array do in bash

i have below part of the code

jmsPort=61015
jmsPorts=(61018 61016 61017)

until [ $jmsPorts -ne $jmsPort ]; do
jmsPort=$(expr $jmsPort + 1)
done


the iteration over the loop is only once in this case, how can use do this ..
until the jmsPorts array does not contain the jmsPort do (jmsPort + 1)

the goal that i want to achieve is

if the jmsPort matches an element in the array:
it should do + 1 to the jmsPort until the jmsPort does not match an element in the jmsPorts array

If the jmsPort is not in the array:
it should choose the jmsPort

i have done this using PowerShell but can't do it in Bash.
the syntax in PowerShell is

$jmsPort = 61016
$jmsPorts = @(61018, 61016, 61017)

do
{
$jmsPort = $jmsPort + 1
}
until ($jmsPorts -notcontains $jmsPort )

Answer

Remember that

jmsPorts=() # jmsPorts is an array

To update the array, initially(before the edit) you've put

jmsPorts+=$(echo $i | grep -oP '\d+') # Wrong

It should've been

jmsPorts+=( "$(echo $i | grep -oP '\d+')" ) #mind the outer brackets.

Now to check if jmsPort doesn't match any element in jmsPorts array do

validator(){
flag=0 # Assuming the element is not present
for i in "${jmsPorts[@]}"
do
 if [ "$1" -eq "$i" ]
 then
  flag=1 # Element is present
 fi
done
}
while validator "$jmsPort" && [ "$flag" -eq 1 ]
do
((jmsPort++))
done

echo "Port Chosen : $jmsPort"  
# This port doesn't match any value in the array.

Warning : Ports 1-65535 are available, and ports in range 1-1023 are the privileged ones. On more complicated scenatios an extra check [ $jmsPort -lt 65535 ] might be necessary.

Comments