1

There is this code:

test2.cpp (compiled to test2 executable):

#include <iostream>

int main(int argc, char** argv)
{
   for(int i = 0; i < argc; ++i){
      std::cout << i << " " << argv[i] << std::endl;
   }
   return 0;
}

test.sh (parameters preparing script):

some_array=("text1" "text two" "text tree")

input_variables=""

for i in $(seq 0 $((${#some_array[*]} - 1))); do
   input_variables="$input_variables --parameter=\"${some_array[$i]}\""
   echo $input_variables
done

echo "Running: ./test2$input_variables"
./test2 $input_variables

Output:

$ sh test.sh
--parameter="text1"
--parameter="text1" --parameter="text two"
--parameter="text1" --parameter="text two" --parameter="text tree"
Running: ./test2 --parameter="text1" --parameter="text two" --parameter="text tree"
0 ./test2
1 --parameter="text1"
2 --parameter="text
3 two"
4 --parameter="text
5 tree"

I would like to pass to test2 executable 3 arguments but 5 arguments are passed and there is a problem with space character between words. I would like also to keep input parameters in array like it is presented in *some_array* so I can add there something whenever I want. How to pass these parameters correctly?

2 Answers 2

2

Embedding quotes (or escapes) in a variable's value doesn't do anything useful. Quotes are parsed before variables are replaced, so by the time the quotes get there it's too late for them to do anything (see BashFAQ #050 for more examples). And BTW using echo to print a command is extremely misleading, use set -x to have the shell print what it thinks is going on.

The best thing to do, as you said in your final note, is to store the parameters in an array:

#!/bin/bash
some_array=("text1" "text two" "text tree")

input_variables=()

for i in $(seq 0 $((${#some_array[*]} - 1))); do
   input_variables+=("--parameter=${some_array[$i]}")
   echo "${input_variables[@]}"
done

printf "Running:"
printf " %q" ./test2 "${input_variables[@]}"
./test2 "${input_variables[@]}"

BTW, arrays are a bash extension, and not always available in plain shells, so you should run this with bash, not sh.

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

Comments

0

Call it in this way:

./test2 try\ 1 try\ 2

You'll get

0 ./test
1 try 1
2 try 2

Command line arguments are automaticly separated by spaces, but if you escape them are get as part of string.

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.