In my shell script, there is a string to keep all arguments
arg_str="arg1=ABC arg2=123 arg3= arg4=\"consecutive spaces and \\\"escaped quote\\\" shall be preserved within quotes\""
I want to split the arg_str
by space but keep anything as is within in double quotes. The expected result is:
arg1=ABC
arg2=123
arg3=
arg4=consecutive spaces and \"escaped quote\" shall be preserved within quotes
This answer can split by spaces outside double quotes, but it cannot preserve consecutive spaces within double quotes.
EDIT
Why I need this? I'm designing a shell script to accept dynamic arguments -- both arg name and value are dynamic, e.g. myscript.sh arg1=ABC arg2=123 arg3= arg4="consecutive spaces and \"escaped quote\" shall be preserved within quotes"
. I'm not good at bash. Someone mentioned getopts
, it seems it not suitable for the situation of dynamic args.