Bash script: array elements containing space character

22,806

Arrays are defined differently:

components=(Persistence Instrument "Accessory Engine")

or

components=(Persistence Instrument Accessory\ Engine)

And accessed differently:

for i in "${components[@]}"
Share:
22,806

Related videos on Youtube

user3611406
Author by

user3611406

Updated on September 18, 2022

Comments

  • user3611406
    user3611406 almost 2 years

    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?

  • user3611406
    user3611406 over 9 years
    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
  • user3611406
    user3611406 over 9 years
    thanks, the last comment fixed it. why do I have to include the " characters in the for loop?
  • PM 2Ring
    PM 2Ring over 9 years
    @lomppi: Quotes are used to prevent unwanted word splitting. See mywiki.wooledge.org/BashGuide/Practices#Quoting