Take the 2-minute tour ×
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.

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
add comment

3 Answers

up vote 4 down vote accepted

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

#!/bin/bash
new_args=()
for arg
do
    new_args+=( '-p' )
    new_args+=( "$arg" )
done

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

Test:

$ ~/test.sh foo $'bar\n\tbaz bay'
-p
foo
-p
bar
    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
add comment

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

ARGS=("$@")
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
add comment

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=""                       
#IFS=" "                       
printf 'newIFS: %q\n' "$IFS"
ARGS=("$@")
ARGS=( ${ARGS[@]/#/-p } )
for ((i=0; i < ${#ARGS[@]}; i++)); do
  echo "$i: ${ARGS[i]}"
done
)

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

share|improve this answer
add comment

Your Answer

 
discard

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.