From array attribute to bash array


#1

Hello guys,

I have two attributes like these:
default['cookbook']['array1'] = [ "a", "b", "c", "d" ]
default['cookbook']['array2'] = [ "x", "y", "z", "w" ]

I need to pass these attributes as variables to a template like this:

template "/tmp/some.sh" do
  source "some.sh.erb"
  owner 'root'
  group 'root'
  mode "0755"
  variables(
      :bash_array1 => node['cookbook']['array1'],
      :bash_array2 => node['cookbook']['array2']
  )
end

In my bash script i need to have two arrays which will have each, the value of the two array above, like this

#!/bin/bash
inputs1=( "a" "b" "c" "d" )
inputs2=( "x" "y" "z" "w" )

Later edit:
If I make the simplest substitution,

#!/bin/bash
inputs1='<% @bash_array1 %>'

The result would be a string like:
inputs1='["a", "b", "c", "d" ]

And I would need to transform it to a bash array with
inputs1=$(echo $inputs | sed "s/\[/( /; s/]/ )/; s/[',]//g")
which would have as a result this:
inputs1=( "a" "b" "c" "d" )
But this is not longer an array, but just a string.

What’s the simpliest way to do it?

Thank you,
Gabriel


#2

Well, there are many possible solutions. How about this:

#!/bin/bash
inputs1=( "<%= @bash_array1.join('" "') %>" )

#3

I already answered you on StackOverflow and gave you all the tools you need to do this. If you want someone to just do it for you, then please hire a consultant. Chef is a programming toolkit at heart and you’ll need to learn how to build things using the basic tools we provide. Use the Erb formatting to experiment, write some different examples, see how it works. There is a sharp learning curve, but the only way out is through.


#4

Thank you for the help. Just FYI, I posted the question here first and then on StackOverflow.
In the meantime I’ve solved my problem.
The thing is that chef’s learning curve is a sharp one as you said, but that because nobody tells you at the beginning that you really need to acquire ruby knowledge as well… and some python knowledge and maybe (if you’re unlucky enough) you need perl or some other string parsing tools…
So any help is appreciated.
Thanks again,
Gabriel