I’ve been stuck on this issue around variable expansion in Bash scripts where a multi-word argument surrounded by spaces is getting split into multiple arguments when passed down a chain of functions.
For example:
"this entire string"
becomes:
"this
entire
string"
Extracting out the arrangement of functions out of the code that it’s causing the issue in, below is what I could come up with to reproduce the issue:
#!/usr/bin/env bash
# The function that gets called from outside the script
wrapper_function () {
echo "1: Parameter count: $#"
for i in "$@"; do
echo "wrapper_function - $i"
done
actual_function $@
}
# The actual low-level function that does something useful
actual_function () {
echo "2: Parameter count: $#"
for i in "$@"; do
echo "actual_function - $i"
done
}
# Setting the value of the 'problematic' argument
some_string=""five-1 five-2""
# Calling the function with a collated set of arguments
wrapper_function "one two three four ${some_string}"
On running this I would get:
1: Parameter count: 1
wrapper_function - one two three four "five-1 five-2"
2: Parameter count: 6
actual_function - one
actual_function - two
actual_function - three
actual_function - four
actual_function - "five-1
actual_function - five-2"
Instead, I expect:
1: Parameter count: 1
wrapper_function - one two three four "five-1 five-2"
2: Parameter count: 5
actual_function - one
actual_function - two
actual_function - three
actual_function - four
actual_function - "five-1 five-2"
Is there anything that I could do to get around this, maybe quoting some arguments or passing them around some other way?
I found a similar question that this one might look like a duplicate of but I think it’s not.