1

I have got a simple script as follows.

names=("windows" "ubuntu" "raspbian" "debian" "kali linux")
echo "names array length: ${#names[@]}"

for n in ${names[@]}; do
    echo $n
done

My intention and hope to get was:

names array length: 5
windows
ubuntu
raspbian
debian
kali linux

but instead the result i got was:

names array length: 5
windows
ubuntu
raspbian
debian
kali
linux

The array seems to have the correct number of entry but printout appears on 6 lines instead of 5. How can i have the desired output?

5

Double quoting the variable expansion ${names[@]} would make it expand to the elements of the array, individually quoted. Not quoting that variable expansion would make the shell split all elements on whitespaces (by default), and additionally perform filename globbing on all the generated words (not an issue with the words that you use). In your example, this would cause kali and linux to be treated as two separate words.

Therefore, use

for name in "${names[@]}"; do
    printf '%s\n' "$name"
done

or, for this simple script,

printf '%s\n' "${names[@]}"

(no loop required since printf will simply reuse its format string for each individual argument)

Related:

Also (why I always use printf for outputting variable strings):

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.