How to add suffix and prefix to $@
?
If I do $PREFIX/$@/$SUFFIX
, I get the prefix and the suffix only in the first parameter.
Let's create a parameters for test purposes:
$ set -- one two three
$ echo "$@"
one two three
Now, let's use bash to add prefixes and suffixes:
$ IFS=$'\n' a=($(printf "pre/%s/post\n" "$@"))
$ set -- "${a[@]}"
$ echo -- "$@"
pre/one/post pre/two/post pre/three/post
Limitations: (a) since this uses newline-separated strings, it won't work if your $@
contains newlines itself. In that case, there may be another choice for IFS
that would suffice. (b) This is subject to globbing. If either of these is an issue, see the more general solution below.
On the other hand, if the positional parameters do not contain whitespace, then no change to IFS
is needed.
Also, if IFS
is changed, then one may want to save IFS
beforehand and restore afterward.
If we don't want to make any assumptions about whitespace, we can modify "$@" with a loop:
$ a=(); for p in "$@"; do a+=("pre/$p/post"); done
$ set -- "${a[@]}"
$ echo "$@"
pre/one/post pre/two/post pre/three/post