Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass arguments include new line character(\n) into C program from command line

I want to pass a shell code(string) in linux, include new line character as arguments into C program from command line, example : ./myprogram "number=0 \n while [ $number -lt 10 ]; do \n echo $number \n number=$((number + 1)) \n done"

if I put this string directly in C code, and use system(command_string), the symbol '\n' is interpreted as newline character and it'll work well. But if I send this string through command line as above it'll not work. the symbol '\n' is not interpreted as newline character. How can I sovle this problem?

like image 550
spectre Avatar asked Oct 12 '25 22:10

spectre


1 Answers

As suggested by squeamish ossifrage's comment, provided that you are using an Unix-like shell (meaning not cmd.exe on Windows ...), a raw newline in a quoted string is interpreted as itself and does not terminate the command.

You should write simply :

./myprogram "number=0
 while [ \$number -lt 10 ]; do 
 echo \$number  number=\$((number + 1)) 
 done"

Beware : no \ before the newline. If you put one, the newline will be taken as a continuation and will be removed.

Edit : but of course $ characters have to be escaped between "...

like image 133
Serge Ballesta Avatar answered Oct 14 '25 16:10

Serge Ballesta