Sample Header Ad - 728x90

Bash manage space separated list

1 vote
2 answers
3313 views
I have a rather complex shell script which processes several list of values which are read from a file as space separated values e.g.
SET1="value1 value2 value3"

for i in ${SET1}; do
   ...
I now want to create a similarly formatted list in the script to write out. However if I do (for example) this:
DISCOVERED=''
DISCOVERED+=( us-east-1 )
DISCOVERED+=( us-east-2 )
DISCOVERED+=( us-west-1 )
for REGION in ${DISCOVERED} ; do
    echo $REGION
done
I get no output. I do get output if I specify in ${DISCOVERED[@]}. It appears I am working with different data types in SET1 and DISCOVERED. I can easily append to a string with space-separated values, but I end up with either a leading or trailing space which needs cleaned up:
function append_discovered {
   local VALUE="$1"
   if [ -z "${DISCOVERED}" ] ; then
      DISCOVERED="$VALUE"
   else
      DISCOVERED="${DISCOVERED} ${VALUE}"
   fi
}
....but this seems rather cumbersome. I could treat my output variable as an array - but then I either need to convert it back (DISCOVERED="${DISCOVERED[@]}") at appropriate places to use a different construct for iterating through this list than I have for the other lists. What is the data type for my input data (e.g. $SET1 above) if not an array? Is there a neater way to append this list and keep the same data type?
Asked by symcbean (6301 rep)
Jul 10, 2023, 04:44 PM
Last activity: Jul 11, 2023, 02:09 PM