I’ve spent last hour or so trying to write a pretty simple bash script and I never felt so dumb.
So I have a list of strings (which are package selector specifications for a package manager, if that matters) which might contain asterisks. I need to build a command line preserving those asterisks and then call a program. Here is my naïve attempt:
xs="foo/bar */*"
xs_cmd=""
for x in $xs; do
xs_cmd="$xs_cmd -0 $x "
done
echo $xs_cmd
I need the echo
call to be equivalent to
echo -0 foo/bar -0 '*/*'
which outputs -0 foo/bar -0 */*
.
P. S. In reality the first line is slightly more complex: xs="$some foo/bar */* $(get_others)"
.
If you run this script in a directory containing a/b
, you’ll get -0 foo/bar -0 a/b
instead.
When I change the last line to
echo "$xs_cmd" # note the quotes
I get -0 foo/bar -0 a/b
and, first of all that’s not what I want, since now I’m invoking echo
with a single argument, and furthermore that tells me that the expansion is happening earlier, likely in the for
loop.
But I can’t change the for
line because
for x in "$xs"; do # note the quotes
will just make the loop iterate only once: -0 foo/bar */*
(there is a single -0
)
so adding those quotes is not an option for sure.
Now if I revert back to the original script and replace the first line with
xs="foo/bar '*/*'" # note additional single quotes
I get -0 foo/bar -0 '*/*'
(single quotes should’t be there).
It seems that I tried every combination of quotes and backslash-escapes of asterisks and I have literally no idea what to do now.