Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over list which contains whitespaces in bash

Tags:

bash

loops

Could you please tell me how to iterate over list where items can contain whitespaces?

x=("some word", "other word", "third word")
for word in $x ; do
    echo -e "$word\n"
done

how to force it to output:

some word
other word
third word

instead of:

some
word
(...)
third
word
like image 779
J33nn Avatar asked Jan 29 '13 16:01

J33nn


2 Answers

To loop through items properly you need to use ${var[@]}. And you need to quote it to make sure that the items with spaces are not split: "${var[@]}".

All together:

x=("some word" "other word" "third word")
for word in "${x[@]}" ; do
  echo -e "$word\n"
done

Or, saner (thanks Charles Duffy) with printf:

x=("some word" "other word" "third word")
for word in "${x[@]}" ; do
  printf '%s\n\n' "$word"
done
like image 77
fedorqui 'SO stop harming' Avatar answered Nov 15 '22 04:11

fedorqui 'SO stop harming'


Two possible solutions, one similar to fedorqui's solution, without the extra ',', and another using array indexing:

x=( 'some word' 'other word' 'third word')

# Use array indexing
let len=${#x[@]}-1
for i in $(seq 0 $len); do
        echo -e "${x[i]}"
done

# Use array expansion
for word in "${x[@]}" ; do
  echo -e "$word"
done

Output:

some word
other word
third word
some word
other word
third word

edit: fixed issues with the indexed solution as pointed out by cravoori

like image 29
imp25 Avatar answered Nov 15 '22 05:11

imp25