简体   繁体   中英

echo command in system api call without \n?

#include <stdio.h>
#include<stdlib.h>


void echoIt()
{
    char* cmd_1 = "echo -ne {\"key\":\"value\"} > outFile";
    char* cmd_2 = "echo -ne ,{\"key1\":\"value1\"} >> outFile";

    system(cmd_1);
    system(cmd_2);
}

int main(int argc, char **argv)
{
    echoIt();
}

output came in 2 lines ,the option -ne is to remove \\n that also came in outFile

root@userx:/home/userx/work/lab/test# cat outFile 

    -ne {key:value}
    -ne ,{key1:value1}

expected result is on the same line :

{key:value} ,{key1:value1}

how to get it?

I'm going to take your word for it that you have a concrete reason why you must use a subshell for this, rather than opening the file directly. The -n and -e options to echo are not part of the portable shell specification. Often, they work in the interactive shell you are accustomed to using, but don't work in the noninteractive shell used to interpret system command lines.

On modern (post-2001) operating systems, it is better to use printf than echo :

system("printf '%s' '{\"key\":\"value\"}' > outFile");
system("printf '%s' ',{\"key\":\"value\"}' >> outFile");

will do what you want. If there's a case where you do want a newline after the string, printf understands C-style backslash escapes in its first argument only:

system("printf '%s\\n' ',{\"key\":\"value\"}' >> outFile");

Pay close attention to the quoting in all of these examples.

echo -n ... is non-standard. Per the POSIX standard for echo :

... If the first operand is -n , or if any of the operands contain a <backslash> character, the results are implementation-defined.

echo is not a good way to emit output when you need to control the formatting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM