0

I'm running a script in Bash on a Mac and I am trying to split a string with the delimiter being a space into an array. The command I'm running is:

array = ($(echo "$string" | tr ' ' "\n"))

that returns the "unexpected '('" error. I've tried multiple solutions including

  • escaping the parentheses
  • putting quotes around the command
  • making sure the space wasn't causing the error
  • making sure my header is #!/bin/bash
dessert
  • 40,956

1 Answers1

6

First of all, assignments in shell scripts should not contain spaces between left-hand side of = ( the variable/array name ) and right-hand side of the assignment operator =. As for converting string to array, you don't need to replace spaces with newlines explicitly, just take advantage of automatic word splitting, which occurs when unquoted variables are called:

$ string='This is a hello world string'
$ array=( $string  )
$ echo ${array[3]}
hello
$ echo ${array[4]}
world