I have a variable with space separated list of paths. I need to send these paths to a program as a parameter like this script.sh -i /dir1 -i /dir2. What is the best way to create such parameter list? Something like $(echo "$paths" | sed 's|\([^[:space:]]\+\)|-i \1|g) will work but it's unreadable given the fact that it's part of the makefile.

link|improve this question

29% accept rate
1  
this question should be moved to stackoverflow – mc9x Oct 18 '11 at 11:20
feedback

2 Answers

up vote 1 down vote accepted
list="one two three"
for i in $list; do params="$params -i $i"; done
script.sh $params

You will have troubles with paths with spaces, using : as paths separator is better

link|improve this answer
feedback

use bash arrays

paths="/dir1 /dir2"
params=()
for path in $paths; do params+=( -i $path ); done
script.sh "${params[@]}"
link|improve this answer
You're correctly quoting the last expansion but none of the others; that will cause problems with spaces in filenames. for path in "$paths"; do params+=( -i "$path" ); done – adaptr Oct 18 '11 at 14:40
No. "I have a variable with space separated list of paths." Therefore, you must not quote $paths in the for statement, and you're guaranteed that $path will not have a space in it. – glenn jackman Oct 18 '11 at 15:21
Ugh, you're right. Brainfart on the silliness of the original question. – adaptr Oct 18 '11 at 15:46
feedback

Your Answer

 
or
required, but never shown

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