Issue
I have an array in Bash that may be empty. I need to convert the array to a single string, placing a single quote around each element, and separating the elements with a single space. For example:
()
:""
("test")
:"'test'"
("foo bar")
:"'foo bar'"
("test" "foo bar")
:"'test' 'foo bar'"
Assume my array is in $array
, and I put the result in $result
. I'm wanting to pass the result as arguments to Maven exec:java
exec.args
, like this:
array=("test" "foo bar")
result= # TODO
mvn exec:java -Dexec.mainClass="org.example.Main" -Dexec.args="$result"
This would be equivalent to:
mvn exec:java -Dexec.mainClass="org.example.Main" -Dexec.args="'test' 'foo bar'"
Importantly, note that if the array is empty, it would be equivalent to:
mvn exec:java -Dexec.mainClass="org.example.Main" -Dexec.args=""
I would have thought that this would have been answered two decades ago—and maybe it has been, but I can't find it. I found Bash script pass arguments to maven, which has no answer. I found various answers relating to joining with a delimiter, but couldn't find anything that would single-quote each element, join with a delimiter, and still produce an empty string if the array is empty.
For example, Concat array elements with comma and single quote - Bash comes very close:
array=("test" "foo bar")
joined=$(printf " '%s'" "${array[@]}")
result="${joined:1}"
mvn exec:java -Dexec.mainClass="org.example.Main" -Dexec.args="$result"
But if the array is empty, I get "''"
when I want ""
. Update: I guess I can do an old-fashioned if
to special-case an empty array. Anyone have anything better?
Solution
You can use @Q
operator (shell parameter expansion - @operator):
array=("test" "foo bar")
result="${array[*]@Q}"
mvn exec:java -Dexec.mainClass="org.example.Main" -Dexec.args="$result"
If both single/double quotes can appear in the array, consider this :
array=("foo'bar" 'foo"bar')
mapfile -t array2 < <(perl -e '
for $_ (@ARGV) {
$q = /"/ ? "'\''" : q["];
print "$q$_$q\n";
}' "${array[@]}")
result="${array2[*]}"
This assumes that only one type of quotes can appear in a single item of the array though.
Answered By - Philippe Answer Checked By - Katrina (WPSolving Volunteer)