2

I have an array of strings, like:

ARR=(aa bb "cc dd")

I want to call an executable with parameter like:

my_executable -f aa -f bb -f "cc dd"

So I need to add a prefix -f to each element of ARR. I did a search and find:

${ARR[@]/#/-f }

However, this will generate something like:

-f aa -f bb -f cc dd

And if I use my_executable ${ARR[@]/#/-f }, it will pass 7 instead of 6 arguments to my_executable. If I double quote the string substitution part, it will generate 3 arguments, i.e. "-f aa" "-f bb" "-f cc dd", which is not what I want either.

How can I do to make it work? Thank you!

2 Answers 2

5

You could create a new array with the elements inserted. Pass the arguments to the program by saying:

"${NEWARR[@]}"

Given your example:

ARR=(aa bb "cc dd")
NEWARR=()
for i in "${ARR[@]}"; do
  NEWARR+=(-f)
  NEWARR+=("$i")
done
for i in "${NEWARR[@]}"; do
  echo "$i";
done

this would produce:

-f
aa
-f
bb
-f
cc dd

Make sure that you quote your variables.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your answer. It seems that NEWARR now has 3 elements, "-f aa" "-f bb" "-f cc dd". But I want it to have 6 elements, -f aa -f bb -f "cc dd". I'm sorry, the title was misleading. I have changed the title.
@devnull Now thats slick!
@jaypal Stupid things happen!
+1, I'd save a line by adding both elements at once doing NEWARR+=('-f' "${i}"), though.
@AdrianFrühwirth That's a good option. However, an extra line wouldn't hurt for the sake of clarity.
0

How about building the argument list as a string that you use to run my_executable?

for i in "${ARR[@]}"do
  arglist+="-f \"$i\" "
done

This will quote all the elements in your array ARR, without quoting the -f (if that matters).

echo $arglist -f "aa" -f "bb" -f "cc dd"

Then you can use

my_executable $arglist

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.