Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do I prefix -p to every argument passed to my function?

Modifying the arguments themselves and creating a new array are both fine.

share|improve this question
Why do you need that? – alex Jul 14 '11 at 5:45
@alex: For pgrep and subsequently strace. i.e. to strace a bunch of processes, given their names. – Mehrdad Jul 14 '11 at 6:14
up vote 4 down vote accepted

This should work nicely even for complicated arguments with whitespace and worse:

for arg
    new_args+=( '-p' )
    new_args+=( "$arg" )

for arg in "${new_args[@]}"
    echo "$arg"


$ ~/test.sh foo $'bar\n\tbaz bay'
    baz bay
share|improve this answer
That looks like it's what I need, but unfortunately I can't figure out how to get it to work for a function, rather than script (which is what you have). Any ideas? – Mehrdad Jul 15 '11 at 5:31
Just cut and paste the whole thing in an argparse() { ... } function block - It works just fine here. – l0b0 Jul 15 '11 at 7:15
Well I think I was actually having a problem with using xargs on the function, but it's fixed now; thanks! – Mehrdad Jul 15 '11 at 7:41

Put the arguments in an array and use bash pattern substitution on them with array substitution and prefix matching:

echo ${ARGS[@]/#/-p }

That replaces the start of each arg with -p<space>.

Unfortunately this does not work properly if you have spaces in your arguments. Spaces are preserved properly with ARGS=("$@"), but not when you do the ${ARGS[@]/#/-p } expansion. You can put double quotes around that expansion, but then you get -p arg1 as a single argument, not two arguments.

If you don't need -p<space> prepended, just -p then putting double quotes around the expansion should work fine. Experiment with and without double quotes around the expansion to see what works best for you.

share|improve this answer

You can preserve the spaces in the ${ARGS[@]/#/-p } expansion if you set the IFS variable to a null string!

# sample code
set -- 1 2 3 'arg with spaces' $'bar\n\tbaz bay'
printf 'oldIFS: %q\n' "$IFS"
#IFS=" "                       
printf 'newIFS: %q\n' "$IFS"
ARGS=( ${ARGS[@]/#/-p } )
for ((i=0; i < ${#ARGS[@]}; i++)); do
  echo "$i: ${ARGS[i]}"

Inside a function you may limit the scope of a modified IFS variable to this function by using declare IFS="".

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.