Skip to content

Instantly share code, notes, and snippets.

@reyjrar
Created May 28, 2013 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reyjrar/5663806 to your computer and use it in GitHub Desktop.
Save reyjrar/5663806 to your computer and use it in GitHub Desktop.
Implement shell escaping, relies on caller to clean up the memory for the escaped string.
/* Escape a set of characters */
char *os_shell_escape(const char *src) {
// Maximum Length of the String is 2xthe current length
char shell_escapes[] = { '\\', '"', '\'', ' ', '\t', ';', '`', '>', '<', '|', '#',
'*', '[', ']', '{', '}', '&', '$', '!', ':', '(', ')' };
char *escaped_string;
int length = 0;
int i = 0;
// Determine how long the string will be
char *iterator = src;
for (; *iterator; iterator++) {
if( strchr(shell_escapes, *iterator) ) {
length++;
}
length++;
}
// Allocate the memory
if( (escaped_string = malloc( length + 1 )) == NULL ) {
// Return NULL
return NULL;
}
memset(escaped_string, '\0', length + 1);
// Escape the escapable characters
iterator=src;
for( i=0; *iterator; iterator++ ) {
if ( strchr(shell_escapes, *iterator) ) {
escaped_string[i] = '\\';
i++;
}
escaped_string[i] = *iterator;
i++;
}
// Return Success
return escaped_string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment