title: Bash: Split quoted string into array
body: <p><code>data.in</code>:</p>
  
  <pre><code>a b c 'd e'
  </code></pre>
  
  <p><code>script.sh</code>:</p>
  
  <pre><code>while read -a arr; do
      echo "${#arr[@]}"
      for i in "${arr[@]}"; do
          echo "$i"
      done
  done
  </code></pre>
  
  <p>Command:</p>
  
  <pre><code>cat data.in | bash script.sh
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>5
  a
  b
  c
  'd
  e'
  </code></pre>
  
  <hr>
  
  <p>Question:</p>
  
  <p>How can I get <code>'d e'</code> as a single element in the array?</p>
  
  <hr>
  
  <p>Update. This is the best I've done so far:</p>
  
  <pre><code>while read line; do
      arr=()
      while read word; do
          arr+=("$word")
      done &lt; &lt;(echo "$line" | xargs -n 1)
      echo "${#arr[@]}"
      for i in "${arr[@]}"; do
          echo "$i"
      done
  done
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>4
  a
  b
  c
  d e
  </code></pre>
  
  <p>However, the following <code>data.in</code>:</p>
  
  <pre><code>"a\"b" c
  </code></pre>
  
  <p>will fail it (and any other script I have found so far, even in the <a href="https://stackoverflow.com/questions/26067249/bash-reading-quoted-escaped-arguments-correctly-from-a-string">dup question</a>):</p>
  
  <pre><code>xargs: unmatched double quote; by default quotes are special to xargs unless you use the -0 option
  </code></pre>
  
  <p>But this input is legal because you can type in command line:</p>
  
  <pre><code>echo "a\"b" c
  </code></pre>
  
  <p>And it runs well. So this is a mismatch in behavior not illegal input.</p>