Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

I'm getting started with bash scripting. I'm working with array elements that contain space characters. In the code below, the third array element is "Accessory Engine". I tried to set the space character using the \ symbol, but this doesn't help.

In the larger routine (not included here), I use the array elements to automatize some stuff with command line tools. Those command line tools would accept "Accessory Engine" as an input.

#!/bin/bash
components="Persistence Instrument Accessory\Engine"
for i in $components; do
  echo ${i}
done

Now the output from this code is:

  Persistence
  Instrument
  Accessory\Engine

But I want it to be:

  Persistence
  Instrument
  Accessory Engine

How can I achieve that?

share|improve this question

marked as duplicate by Gilles Jan 28 at 21:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

up vote 1 down vote accepted

Arrays are defined differently:

components=(Persistence Instrument "Accessory Engine")

or

components=(Persistence Instrument Accessory\ Engine)

And accessed differently:

for i in "${components[@]}"
share|improve this answer
    
thanks for the input, I've tried both, but I still get the same issue: #!/bin/bash components=(one two three\ four) for i in ${components[@]}; do echo $i; done –  lomppi Jan 28 at 8:01
    
thanks, the last comment fixed it. why do I have to include the " characters in the for loop? –  lomppi Jan 28 at 8:02
2  
@lomppi: Quotes are used to prevent unwanted word splitting. See mywiki.wooledge.org/BashGuide/Practices#Quoting –  PM 2Ring Jan 28 at 8:07
1  
@lomppi It is not relevant for this problem (but if there are two or more successive spaces) but in general you should get used to using quotes: echo "${i}" –  Hauke Laging Jan 28 at 8:09
    
@HaukeLaging thanks! –  lomppi Jan 28 at 8:25

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