[英]How to Properly Escape Nested Special Characters
我需要將下面的例句保存為一個名為demo.sh
的文件。
#!/usr/bin/env bash
xmessage This is "first sentence"
xmessage This is 'second sentence'
xmessage This is {third sentence}
我在C語言中使用的代碼如下:
#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;
}
我可以將以上4句話中的第一句話寫到文件中。 但是其他句子包含特殊字符,例如single quotes
, double quotes
和line ending character
。 而這會非常難以逃脫,因為sudo
命令需要有兩個嵌套的部分,我試圖通過包裝'
和"
分開。
如何轉義句子並將其寫出到文件中? 具有某些功能會很棒,因為實際上該文件超過4個句子並且具有許多特殊字符。
需要注意的是,我知道我可以使用C的I / O功能,我想通過一個使用sudo
, printf
和one line string
system
命令來寫入文件。
我不認為這是最好的方法,但是您可以將一個char []變量用於系統命令,並將sprintf()函數用於在此變量中拆分和寫入命令
這是一個例子
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.