1

I have this script:

#!/usr/bin/env bash

read -p "Provide arguments: " -a arr <<< "foo \"bar baz\" buz"
for i in ${arr[@]}
do
    echo $i
done

which incorrectly outputs:

foo
"bar
baz"
buz

How can I make it interpret user input so that parameters within quotation marks would make a single array element? Like this:

foo
bar baz
buz

EDIT: To be clear: I don't want the user to input each element in separate line, so read-ing in loop is not what I'm looking for.

Maciej Sz
  • 11,151
  • 7
  • 40
  • 56
  • I was thinking on doing `IFS=""; read -p "Provide arguments: " -a arr <<< "$var"` and having a new line in between every element, but it is not working to me. – fedorqui Jan 16 '14 at 13:09
  • If you're _reading_ input from STDIN, the only option seems to input using a delimiter, e.g. `foo;bar baz;buz`. – devnull Jan 16 '14 at 13:27
  • Ok, but how? `Provide arguments: foo; bar baz; buz` does not seem to work either. It reads `foo;` (with the colon) as one element. `GNU bash, version 4.2.25(1)-release (x86_64-pc-linux-gnu)`. – Maciej Sz Jan 16 '14 at 13:49
  • @MaciejSz Of course you'd need to change the code a bit. See the answer. – devnull Jan 16 '14 at 13:58

1 Answers1

2

You're better off supplying user input using a different delimiter, e.g. ;.

OLDIFS=$IFS
IFS=$';'
read -p "Provide arguments: " -a var
for i in "${!var[@]}"
do
    echo Argument $i: "${var[i]}"
done
IFS=$OLDIFS

Upon execution:

Provide arguments: foo;bar baz;buz
Argument 0: foo
Argument 1: bar baz
Argument 2: buz

Plus a modification to trim the variables:

echo Argument $i: $(echo "${var[i]}" | sed -e 's/^ *//g' -e 's/ *$//g')
Maciej Sz
  • 11,151
  • 7
  • 40
  • 56
devnull
  • 118,548
  • 33
  • 236
  • 227
  • Ok, I can settle for this. Thanks :) Just one modification: trimming from [this answer](http://stackoverflow.com/questions/369758/how-to-trim-whitespace-from-bash-variable). – Maciej Sz Jan 16 '14 at 14:22
  • 1
    Nice; you could do `IFS=$';' read ...` (on the same line, localizing the `$IFS` change to that command), in which case there's no need to save and restore `$IFS` via `$OLDIFS`. – mklement0 Jan 16 '14 at 14:34