1

I am creating an array from the output of a command and then i am looping through the array and running commands that use each item in the array. Before i loop through the array i want to create a variable that uses one of the values in my array. I will use this value when one of the items in the array contains a specific string.

I am not sure how to pick the value i need to set the variable from my array before i then loop through the array. I currently have this which is not working for me. I have also tried looping through to get my value but the value does not follow to the next loop, i dont think its being set and i cant keep the loop open as i am looping inside my loop.

readarray -t ARRAY < <( command that gets array of 5 hostnames )
if [[ $ARRAY[@]  == *"FT-01"* ]]; then
FTP="$ARRAY"
fi

for server in "${ARRAY[@]}"; do

echo "Server: ${srv}"
echo "-------------------"
if [[ $server == *"ER-01"* ]]; then
echo " FTP server is ${FTP} and this is ${server}"
fi
done

I'm pretty sure the first if statement would never work but i am at a loss to how to pick out the the value i need from the array.

3
  • Why do you do this with bash instead of awk? Commented Oct 30, 2019 at 12:34
  • I have troubles understanding your question, partly due to formulations like "off the back" and partly because the formulations are very broad (for instance, "the value" – which value exactly?). Also, your script has a loop variable srv but uses $server. Please try to rephrase your question, fix and format your script, and maybe add a concrete example (something like "I have the array ..., because it contains ... I want to do ..."). Commented Oct 30, 2019 at 12:36
  • Edited to be clearer, i am looking for a value in my array that matches a string and then i am going to set a variable that is that value. Commented Oct 30, 2019 at 12:43

1 Answer 1

1

Sometimes difficulty expressing an idea is a sign that you're thinking like a C programmer rather than a shell scripter. Arrays and for loops aren't the most natural idioms in shell scripts. Consider streaming and pipes instead.

Let's say the command that gets hostnames is called list-of-hostnames. If it prints one host name per line you can filter the results with grep.

FTP=$(list-of-hostnames | grep FT-01)

If you really do want to work with an array you could use printf '%s\n' to turn it into a grep-able stream.

FTP=$(printf '%s\n' "${ARRAY[@]}" | grep FT-01)
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh amazing i was so focused on my array i didn't think to just pipe it and pick out my line! thanks this has achieved exactly what i was after

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.