I'm reducing the question to (I believe) the simplest case. Let's say I have a script myscript.sh
with the following contents:
#!/bin/bash
IFS='%20'
echo "$*"
If I run the command as follows, the output will look like:
me@myhost ~ $ ./myscript.sh fee fi fo fum
fee%fi%fo%fum
This is expected behavior, as described in the bash
man page:
* Expands to the positional parameters, starting from one. When
the expansion occurs within double quotes, it expands to a sin-
gle word with the value of each parameter separated by the first
character of the IFS special variable. That is, "$*" is equiva-
lent to "$1c$2c...", where c is the first character of the value
of the IFS variable. If IFS is unset, the parameters are sepa-
rated by spaces. If IFS is null, the parameters are joined
without intervening separators.
However, what I would like to get is the output:
fee%20fi%20fo%20fum
Thus using a multiple character separator field rather than a single character.
Is there a way to do this that is native to bash
?
UPDATE:
Based on the data from mikeserv below, and the writeup at Why is printf better than echo?, I ended up doing the following (again reduced to simplest case as in the example above):
#!/bin/bash
word="$1"
shift
if [ "$#" -gt 0 ] ; then
word="$word$(printf '%%20%s' "$@")"
fi
printf '%s\n' "$word"
unset word
printf %s%%20 "$@"
but that will do an extra one on the tail of the output. if you can be sure none of the args might be misinterpreted there isprintf %b%%20 "$@\c"
. else you can do:for arg do shift; set -- "$@" %20 "$arg"; done; shift; printf %s "$@"
– mikeserv Oct 12 '15 at 04:24printf
and stop leaning onecho
.... – Wildcard Oct 12 '15 at 04:42word=$1${2+$(shift;printf %%20%s "$@")}
- and you don't even have to lose$1
because it only gets shifted in the subshell. – mikeserv Dec 17 '15 at 04:21