Bash declarative list definition for loop

In bash, I often create scripts where I iterate over the list of strings that I define.

eg.

for a in 1 2 3 4; do echo $a; done

However, I would like to define a list (before the loop saves it) so that it contains spaces without a separate file:

eg. (BUT THIS DOES NOT WORK)

read -r VAR <<HERE
list item 1
list item 2
list item 3
...
HERE

for a in $VAR; do echo $a; done

Expected result above (I would like):

list item 1
list item 2
list item 3
etc...

But you will get:

list
item
1

I could use arrays, but I would need to index every element in the array (EDIT reads the answers below, as you can add to arrays .. I did not know what you could).

How do others declaratively define lists in bash without using separate files?

Sorry to forget to mention that I want to define a list at the top of the file before the loop loop logic

+3
source share
5

:

readarray <<HERE
this is my first line
this is my second line
this is my third line
HERE

# Pre bash-4, you would need to build the array more explicity
# Just like readarray defaults to MAPFILE, so read defaults to REPLY
# Tip o' the hat to Dennis Williamson for pointing out that arrays
# are easily appended to.
# while read ; do
#    MAPFILE+=("$REPLY")
# done

for a in "${MAPFILE[@]}"; do
    echo "$a"
done

, , .

+3

"" :

while read a ; do echo "Line: $a" ; done <<HERE
123 ab c
def aldkfgjlaskdjf lkajsdlfkjlasdjf
asl;kdfj ;laksjdf;lkj asd;lf sdpf -aa8
HERE
+4
while read -r line
do
    var+=$line$'\n'
done <<EOF
foo bar
baz qux
EOF

while read -r line
do
    echo "[$line]"
done <<<"$var"

? .

array+=(value)
for item in "${array[@]}"
do
    something with "$item"
done
+3

, \n for, IFS.

read -d \n -r VAR <<HERE
list item 1
list item 2
list item 3
HERE

IFS_BAK=$IFS
IFS="\n"
for a in $VAR; do echo $a; done
IFS=$IFS_BAK
+2

while for, while read " ":

#!/bin/bash

while read LINE; do
    echo "${LINE}"
done << EOF
list item 1
list item 2
list item 3
EOF

ref: ` cat < < EOF` bash?

0

All Articles