简体   繁体   中英

How to Properly Escape Nested Special Characters

I need to save below example sentences as a file called demo.sh .

#!/usr/bin/env bash   
xmessage This is "first sentence"
xmessage This is 'second sentence'
xmessage This is {third sentence}

The code I use in C is below:

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

int main()
{
    system("sudo bash -c 'printf \"#!/usr/bin/env bash\n\" > /usr/share/applications/demo.sh'");
    return 0;
}

I can write the first sentence of the above 4 sentences OK into the file. But the other sentences contain special characters like single quotes , double quotes and line ending character . And this gets very difficult to escape because sudo command needs to have two nested section which I tried to wrap by ' and " separately.

How can I escape the sentences and write out to the file? It would be great to have some function because actually the file is more than 4 sentences and have many special characters.

As a note, I know I could use I/O functions of C, I want to write the file by a single system command which use sudo , printf and one line string .

I dont thing that its the best way, but you can use one char[] variable for system command and sprintf() function to split and write command in this variable

here is an example

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

int main()
{
    char command[128];

    /* Generate string */
    sprintf(command, "sudo bash -c %s %s bash\n > /usr/share/applications/demo.sh'", 
        "'printf", "#!/usr/bin/env");

    system(command);
    return 0;
}

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