title: Bash: Split a string exactly like Readline would split it
body: <p>Given a string representation of an arbitrary Bash "<a href="http://www.gnu.org/software/bash/manual/bashref.html#Simple-Commands" rel="nofollow">simple command</a>", how can I split it into an array containing its individual "parts", i.e. the command name and individual parameters, <strong>just like the the shell itself (i.e. Readline) would split it</strong> when parsing it and deciding which executable/function to run and which parameters to pass it?</p>
  
  <hr>
  
  <p>My specific use-case is needing to parse user-defined alias definitions. E.g. an alias might be defined as:</p>
  
  <pre class="lang-bsh prettyprint-override"><code>alias c2="cut -d' ' -f2"  # just an example... arbitrary commands should be handled!
  </code></pre>
  
  <p>And this is how my bash script would try to parse it:</p>
  
  <pre class="lang-bsh prettyprint-override"><code>alias_name="c2"
  alias_definition=$(alias -p | grep "^alias $alias_name=") # "alias c2='cut -d'\'' '\'' -f2'"
  alias_command=${alias_definition##alias $alias_name=}     # "'cut -d'\'' '\'' -f2'"
  alias_command=$(eval "echo $alias_command")               # "cut -d' ' -f2"
  
  alias_parts=($alias_command) # WRONG - SPLITS AT EVERY WHITESPACE!
  
  echo "command name: ${alias_parts[0]}"
  
  for (( i=1; i &lt;= ${#alias_parts}; i++ )); do
    echo "parameter $i : ${alias_parts[$i]}"
  done
  </code></pre>
  
  <p><strong>Output:</strong></p>
  
  <pre class="lang-none prettyprint-override"><code>command name: cut
  parameter 1 : -d'
  parameter 2 : '
  parameter 3 : -f2
  </code></pre>
  
  <p><strong>Desired output:</strong></p>
  
  <pre class="lang-none prettyprint-override"><code>command name: cut
  argument 1  : -d' '
  argument 2  : -f2
  </code></pre>
  
  <p><br>What would I need to replace the <code>alias_parts=($alias_command)</code> line with, to achieve this?</p>