1

I've an YAML array:

myarray:
    - PHP
    - Perl
    - Python

How to convert it into bash array with ruby ?

Arr[0]='PHP'
Arr[1]='Perl'
Arr[2]='Python'
2
  • 2
    What do you mean convert it into bash array? What are you actually trying to do? Commented Jan 23, 2015 at 13:53
  • I want to create a config.sh from an yaml file for a vagrant box... Commented Jan 23, 2015 at 13:56

3 Answers 3

3

I'm not sure if this is what you want.

In ruby, parse the yaml array and write an output for Bash to read as an array:

require 'yaml'

yaml_array = <<-eos
myarray:
    - PHP
    - Perl
    - Python
eos

yaml = YAML.load(yaml_array)
print "(#{yaml["myarray"].join(' ')})"

This ruby script will print (PHP Perl Python) to stdout.

You can then use it in Bash:

$ eval array=$(ruby ruby_script.rb)
$ echo ${array[0]}
PHP
$ echo ${array[1]}
Perl
Sign up to request clarification or add additional context in comments.

2 Comments

Great ! It's as I want. Thanks a lot
This will be safer for the shell side: print "(\"#{yaml["myarray"].join('" "')}\")" -- contain any element that contains whitespace
2
require 'yaml'

yaml_text = "myarray:
    - PHP
    - Perl
    - Python"

yaml = YAML.load(yaml_text)
array = yaml["myarray"]

puts array.class #=> Array
puts array       #=> PHP
                 #=> Perl
                 #=> Python

Comments

2

The bash mapfile command is useful to convert lines of stdin into an array:

$ cat file.yaml 
myarray:
    - PHP
    - Perl
    - Python
    - element with spaces

$ mapfile -t array < <(ruby -ryaml -e 'yaml = YAML.load(File.read(ARGV.shift)); puts yaml["myarray"].join("\n")' file.yaml)

$ for i in "${!array[@]}"; do echo "$i  ${array[i]}"; done
0  PHP
1  Perl
2  Python
3  element with spaces

This avoids having to use eval in the shell

1 Comment

NIce function indeed but only avail in bash 4+ which I do not have unfortunately (just to warn others)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.