2

I have a C program "main" which gets the following parameters:

"a b c d ..." e f g

That's a total of 4 parameters, because of the quotation. I have a text file which each line has these 4 parameters. I made a shell script to run the C program for each of the parameters:

#!/bin/bash
while read line
do
    ./main "$line"
done < $1

The problem is that the C program is recognizing the first parameter, which is quoted, as several separated parameters, as if the quote was being ignored. Among the many things I've tried, it's worth mentioning that I tried changing each quotation in the file to \" and even remove the quotation from the call (./main $line).

1 Answer 1

2
#!/bin/bash
while read line
do
    eval set -- $line
    ./main "$@"
done < $1
Sign up to request clarification or add additional context in comments.

4 Comments

Why eval? Shouldn't it work fine with just set -- $line?
parameters seem to be escaped (e.g. "a b c d" e f) so they must be passed through eval. If you do not believe me, just test it ;) echo '"1 2 3 4" a b c' | bash -x /tmp/xxxx.sh
eval set -- $line works, thanks. But I'm not quite sure why (I'm not that experienced in shell scripting). My explanation would be: set -- $line sets the arguments passed to the shell, for some reason I'm unaware of; then eval evaluates it so that $line can be interpreted accordingly, which is going to take the quote into account. Is that correct? Why does set -- $line sets the arguments passed to the shell, namely, $@? Or it doesn't?
eval causes it to be interpreted as when you type set -- "1 2 3 4" a b c. Without, it will be interpreted as set -- \"1 2 3 4\" a b c; e.g. the " is taken literally. set sets the positional parameters ($@); the -- is used to avoid interpretation of - in front following args.

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.