I'm working on a Bash function that processes a list of arguments formatted as `"--key=value"` and reformats them to `"--key value"`. For example, `"aaa --option=bbb ccc"` becomes `"aaa --option bbb ccc"`. Here's the function I'm using:
```bash
expand_keyval_args() {
local result=()
for arg in "$@"; do
if [[ "$arg" == --*=* ]]; then
key="${arg%%=*}"
value="${arg#*=}"
printf "%s %q " "${key}" "${value}"
else
printf "%q " "${arg}"
fi
done
}
```
I handle values that contain whitespace by using `"%q"` in `printf`, and then process an array like this:
```bash
local args=( ... )
local out="$(expand_keyval_args "${args[@]}")"
eval "args=(${out})"
```
I'm wondering if this is the best approach or if there's a more efficient method that avoids using `eval`. I know some suggested using `getopt`, but my issue is broader: I need a reliable way to manage arrays that may contain any character, including spaces and quotes. Any suggestions?
1 Answer
You might want to look into `getopt` or `getopts` for argument parsing. They've been around a while and can handle a lot of these issues without you needing to reinvent the wheel. Just keep in mind that if you're changing syntax, using something like `--key "string"` instead of `--key=value` could simplify things a lot!
Related Questions
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically
[Centos] Delete All Files And Folders That Contain a String