0

I want to populate a bash array by splitting one of the arguments based on the space but preserving the escaped space or double quotes.

populate_array() {
  params="${1}"
  array=(-j $params)
  for elem in "${array[@]}"
  do
    echo "${elem}"
  done
}

cols="x\ y"
populate_array "${cols}"

Output:

-j
x\
y

Desired output:

-j
x y

I even tried escaped double quotes

populate_array() {
  params="${1}"
  array=(-j $params)
  for elem in "${array[@]}"
  do
    echo "${elem}"
  done
}

cols="\"x y\""
populate_array "${cols}"

Output:

-j
"x
y"

Desired output:

-j
x y

FYI it can be easily done using eval, but I'd rather prefer not to do that. The answers https://stackoverflow.com/a/31485948/3086551 explain by either taking human generated input or reading from the file. I want to parse the passed argument with escaped space or double quotes instead.

user3086551
  • 405
  • 1
  • 4
  • 13
  • Updated the question. The real issue occurs when passing string with escaped spaces or double quotes as an argument. – user3086551 May 18 '18 at 18:02
  • Could you explain why the linked duplicates don't apply to that "real issue", or show how you've tried to apply their advice without success? The only thing that looks pertinent to me is that you want to prepend `-j` to the generated array, and many of the possibilities listed include an `array=( )` step that could just be changed to `array=( -j )` to do so. – Charles Duffy May 18 '18 at 18:02
  • (btw, I'll be stepping out to lunch in a few minutes, so there might be some lag if nobody else is actively keeping an eye -- but if you *do* edit to clarify this to distinguish from previously-answered questions on the subject, either I or another dupehammer-wielder in the tag will be able to reopen; an edit will also put it on the review queue for possible reopening, so it's possible that the necessary five votes from the general public could happen in that time period as well). – Charles Duffy May 18 '18 at 18:06
  • The explained answers either taking human generated input or reading from a file. Both of them doesn't apply to my question. I need to parse an argument to populate the array. None of the answers explain the argument parsing way. – user3086551 May 18 '18 at 18:23
  • 1
    The "from a string" answer works with *any* string. It doesn't matter if that string was taken off an argument list or not. – Charles Duffy May 18 '18 at 18:24
  • 1
    See https://ideone.com/zvON8n for a working example of your `populate_array` function using the xargs approach from the duplicates. – Charles Duffy May 18 '18 at 18:29
  • @CharlesDuffy Thank you so much, Charles! It is working as expected. – user3086551 May 18 '18 at 21:15

0 Answers0