How to iterate over values with space characters?

Viewed 33

I have the following:

directories="directory_1 directory_2"
for k in ${directories}; do 
    echo "${k}"
done;

The problem is that if I add a directory with a blank space in its name, e.g. directory 3, this fails as it is treated as two strings.

1 Answers

Use an array:

A=(
  foo 
  "bar a" 
  blub
)

for k in "${A[@]}"; do
  echo "$k"
done

prints:

foo
bar a
blub

You can read more about arrays in the manual page man bash (search for arrays with "/ Arrays" and use n to move to the next site. h lists more commands) or in the Beginners Guide.

Related