I looked around for an answer to the question "Can I use an array as an environment variable and then call it from a Bash shell script" and came to the conclusion that it was not "officially" supported as (outlined here, and here).
However I really had a need to do this and came up with a "work-around" and wanted to get your opinions.
Setup: I created a variable in my .profile
file that looks something like:
HOST_NAMES='server1 server2 server3'
Then at the begining of my shell script I wrote:
SRVR_ARRAY=($(echo $HOST_NAMES | awk '{for (i = 1; i <=NF; i++) print $i " "}'))
Later on in the script when it was time to do some work, I called:
for h in "${SRVR_ARRAY[@]}"; do
ping $h
done
And it worked! Now I'm sure this is Bash shell scripting jerry-riggin at its finest but wanted to see if anyone could see any risks in this usage?
SRVR_ARRAY=($HOST_NAMES)
? – Michael Homer Mar 23 '17 at 05:06server1 server2 server3
– JuanD Mar 23 '17 at 05:21SRVR_ARRAY=($HOST_NAMES)
, the list of host names will be split, and each name stored as a separate entry in the array. As Michael said, try it. BTW, neither is entirely safe if any of the host names might contain whitespace (technically, that means any of the characters in$IFS
, which actually might be anything) and/or shell wildcards (*
,?
, or[
). – Gordon Davisson Mar 23 '17 at 05:22$IFS
to something nonstandard? – Gordon Davisson Mar 23 '17 at 05:23SRVR_ARRAY=($HOST_NAMES)
and it worked. – JuanD Mar 23 '17 at 05:30SRVR_ARRAY
at all. Why not dofor h in $HOST_NAMES; do ping $h; done
? – Philippos Mar 23 '17 at 06:49-Thanks to everyone for their input.
– JuanD Mar 23 '17 at 11:47