What’s the best way to handle an array with whitespace in arguments using Bash?

0
1
Asked By CuriousCoder92 On

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

Answered By TechieTom On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.