Given a string representation of an arbitrary Bash "simple command", how can I split it into an array containing its individual "parts", i.e. the command name and individual parameters, just like the the shell itself (i.e. Readline) would split it when parsing it and deciding which executable/function to run and which parameters to pass it?
My specific use-case is needing to parse user-defined alias definitions. E.g. an alias might be defined as:
alias c2="cut -d' ' -f2" # just an example... arbitrary commands should be handled!
And this is how my bash script would try to parse it:
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 <= ${#alias_parts}; i++ )); do
echo "parameter $i : ${alias_parts[$i]}"
done
Output:
command name: cut
parameter 1 : -d'
parameter 2 : '
parameter 3 : -f2
Desired output:
command name: cut
argument 1 : -d' '
argument 2 : -f2
What would I need to replace the alias_parts=($alias_command)
line with, to achieve this?