Why does this function handle argument escaping correctly?

April 19, 2025 2 answers
Asked by cardinal.direction
I'm trying to understand why this function is able to preserve argument escaping properly. I have a decent grasp of what's happening, but there are still a few things that confuse me. I'm particularly interested in whether there's a better way to achieve this in POSIX shell that works effectively. The goal of my implementation is to receive strings for "before" and "after", parse them both as an argument list, and create an array that represents that argument list while respecting proper grouping of quotes. Here's the part of the code that seems to work: ```bash arg2list() { local toset=$1 shift 1 eval "$toset=($@)" } ``` In the context of the functions generating C code, the strings passed through `$1` and `$2` are space-separated values passed in with `--add-flags`. I've tried multiple approaches, and while this method works, I'm still curious if there might be a more effective solution. One attempt I made doesn't work on macOS, and I'm hoping to find a solution that universally works across environments. Any insights you have would be greatly appreciated!

Answers

frayed cuffs
When you place `$@` in quotes, it treats everything as a single string and prevents any globbing or unexpected expansions of the values. Despite the warnings, the use of `eval` in this context is actually necessary to achieve the desired outcome of structured data. Setting `noglob` before the command avoids unwanted globbing at the current stage, which is crucial for the safe passing of arguments.

~a little rusty: So this means it's correct even with the shellcheck warnings? Also, did `noglob` help prevent any issues with unwanted expansions during execution?

Reply to this answer
_67 words
This situation seems like a classic case of 'quoting hell'. I recommend avoiding `eval` and instead using name references. For instance, you can set up your `arg2list` function like this: ```bash your_function() { local -n ref=$1 readarray -d '' ref < <(printf '%s' "${foo}" "${bar}") } ``` Using `` as a delimiter lets you preserve the integrity of the arguments without the pitfalls of `eval`. It's a cleaner approach that keeps the arguments neatly separated, making the code easier to manage.

a question of scale: This approach sounds promising! Have you tried implementing it in your current setup?

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions