Skip to content

Instantly share code, notes, and snippets.

@kugland
Last active June 18, 2018 01:44
Show Gist options
  • Save kugland/b9d6e9689f613ff1e3593749f25a5e9e to your computer and use it in GitHub Desktop.
Save kugland/b9d6e9689f613ff1e3593749f25a5e9e to your computer and use it in GitHub Desktop.
Escapes a string for use with bash shell, formatted as $'...'.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
/**
* Escapes a string for use with bash shell, formatted as $'...'.
*
* @param input the input string you want to escape.
*
* @return the escaped string (which must be free'd after use).
*/
char* shell_escape(const char* input)
{
int c;
const char *p;
char *q;
char *result;
size_t length;
/* If the input is NULL, then return NULL */
if (input == NULL)
return NULL;
/* First, compute how much space will be required for the escaped string. */
p = input, length = 4;
while ((c = *p++ & 255) != 0) {
length++;
if (c < 32 || c >= 128) {
length += 3;
} else if (c == '"' || c == '\'' || c == '?') {
length++;
}
}
/* Then allocate a char array for the result. */
if ((result = (char *) malloc(length)) == NULL)
return NULL;
/* Finally, escape the string. */
p = input, q = result;
*q++ = '$';
*q++ = '\'';
while ((c = *p++ & 255) != 0) {
if (c < 32 || c >= 128) {
*q++ = '\\';
*q++ = (c >> 6 & 3) + '0';
*q++ = (c >> 3 & 7) + '0';
*q++ = (c >> 0 & 7) + '0';
} else if (c == '"' || c == '\'' || c == '?') {
*q++ = '\\';
*q++ = c;
} else {
*q++ = c;
}
}
*q++ = '\'';
*q++ = 0;
/* We should have arrived at a string whose length is equal to the value
of the variable “length”. */
assert((q - result) == length);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment