Vagho Vagho - 1 year ago 97
Bash Question

until item does not exists in array do in bash

i have below part of the code

jmsPorts=(61018 61016 61017)

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

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)

$jmsPort = $jmsPort + 1
until ($jmsPorts -notcontains $jmsPort )

Answer Source

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

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download