在C中,我应该使用什么函数来转义shell命令参数的字符串?
This is a string with () charactersecho This is a string with () charactersecho "This is a string with () characters"
echo This is a string with \(\) charactersC中是否有将#2转换为#3的预定义函数?
发布于 2010-09-08 16:22:49
将'的所有实例替换为'\'',然后用单引号(')封装整个字符串是一种安全的方法。这甚至适用于嵌入的新行。另一种方法是在每个字符之前插入\,但必须对换行符进行一些特殊处理,因为\后面的换行符被shell忽略,而不是作为文字换行符来处理。您必须用' (单引号)包围换行符。
发布于 2010-09-08 15:08:56
发布于 2012-08-07 21:44:02
C不是我所选择的语言,但我想出了一个问题(我自己也必须回答同样的问题)。
#include <stdio.h> // sprintf
#include <stdlib.h> // malloc
#include <string.h> // strlen
char* escapeshellarg(char* str) {
char *escStr;
int i,
count = strlen(str),
ptr_size = count+3;
escStr = (char *) calloc(ptr_size, sizeof(char));
if (escStr == NULL) {
return NULL;
}
sprintf(escStr, "'");
for(i=0; i<count; i++) {
if (str[i] == '\'') {
ptr_size += 3;
escStr = (char *) realloc(escStr,ptr_size * sizeof(char));
if (escStr == NULL) {
return NULL;
}
sprintf(escStr, "%s'\\''", escStr);
} else {
sprintf(escStr, "%s%c", escStr, str[i]);
}
}
sprintf(escStr, "%s%c", escStr, '\'');
return escStr;
}给定escape'this',它将输出'escape'\''this'\''',然后可以传递给echo。
$ echo 'escape'\''this'\'''
escape'this'https://stackoverflow.com/questions/3668928
复制相似问题