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).

Novice
  • 115
  • 7

1 Answers1

2
#!/bin/bash
while read line
do
    eval set -- $line
    ./main "$@"
done < $1
ensc
  • 6,704
  • 14
  • 22
  • Why `eval`? Shouldn't it work fine with just `set -- $line`? – Dietrich Epp Nov 20 '13 at 00:58
  • 1
    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` – ensc Nov 20 '13 at 01:03
  • _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? – Novice Nov 20 '13 at 01:48
  • `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. – ensc Nov 20 '13 at 02:01