0

I have a variable that when echoed looks like the following:

var1
var one
var_one
var_one (1)

And I'd like to read it line-by-line into an array but when I do I get this error:

-sh: cannot open var1
var one
var_one
var_one (1): File name too long

And I'm using this command:

read -a names < $myVar

hax0r_n_code
  • 5,332
  • 11
  • 55
  • 95
  • see http://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash using \n as delimiter – smcg Aug 27 '13 at 15:36

1 Answers1

2

You need to use a herestring:

read -a names <<< $myVar

< $myVar is telling the shell to read from a file named by the contents of $myvar, that is, a file named var1\nvar one\nvar_one\nvar_one (1) (with literal newlines). Obviously that file doesn't exist, so you're getting the error. <<< $myVar tells the shell to read the contents of the variable itself as the input, not a file named by it.

If a shell doesn't have the herestring, you'll have to echo it:

echo "$myVar" | read -a names
Kevin
  • 48,059
  • 14
  • 92
  • 127
  • This works under a normal bourne shell but not in my esxi bourne shell. Are there other techniques to accomplish this? – hax0r_n_code Aug 27 '13 at 15:45
  • I'm not familiar with esxi, but it should at least work with `echo`, I've added that. – Kevin Aug 27 '13 at 15:51