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
  • 39,392
  • 12
  • 115
  • 163
javarookie
  • 3
  • 1
  • 1
  • 2
  • 2
    Please install `shellcheck` to help you debug scripts: `sudo apt-get install shellcheck` – George Udosen Jun 22 '18 at 20:42
  • Possible duplicate of https://askubuntu.com/questions/21136/how-to-debug-bash-script – David Foerster Jun 23 '18 at 19:31
  • 2
    reference to Mac not irrelevant - macs use an ancient version of Bash. Reopen to close as dupe of ultra generic question? No thanks. Please ask on [apple.se] or [unix.se] – Zanna Jun 23 '18 at 19:50
  • @Zanna Granted OP uses Mac, but the syntax of such basic thing as variable assignment and command substitution has been the same through multiple versions of bash, and in fact `var_name=word` , that is no-space between name, `=`, and `word` is POSIX-specified, so . . . version is actually irrelevant here and non-Mac specific. – Sergiy Kolodyazhnyy Jun 23 '18 at 20:31
  • or use http://www.shellcheck.net/ online. – Cyrus Jun 24 '18 at 08:16

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
Sergiy Kolodyazhnyy
  • 103,293
  • 19
  • 273
  • 492