Given the bash parameter
foo='ab "cd" "e f" x="1 2" '
I wish to produce an array equivalent to
foo_transformed=( ab '"cd"' '"e f"' 'x="1 2"' )
in a portable way, meaning using either bash (v3+) builtins or programs available to most operating systems (Linux, Unix, Cygwin) by default. Simplicity and safety, given (almost) arbitrary input string, are desirable.
You may assume the input does not contain single quotes '
or backslashes \
, but may contain an arbitrary number of whitespace characters, both where I wish them to delimit the string and where they do not (when inside double quotes).
If we try:
foo_transformed=( $foo )
then the internal quotes of foo
are not respected (for k in "${foo_transformed[@]}"; do echo "- $k"; done
):
- ab
- "cd"
- "e
- f"
- x="1
- 2"
If we try:
eval foo_transformed=( $foo )
then the quotes are lost:
- ab
- cd
- e f
- x=1 2
eval "declare -a foo_transformed=($foo)"
. – Dressel