C is not my choice language, but here is what I came up with (to answer the same question myself).
#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; }
Given escape'this' , it will output 'escape'\''this'\''' , which can then be passed to echo .
$ echo 'escape'\''this'\''' escape'this'
N13
source share