Search code examples
cshellfunctionescaping

C function to escape string for shell command argument?


What function should I use to escape strings for shell command argument in C?

  1. I have a string:

    This is a string with () characters

  2. This will be error:

    echo This is a string with () characters

  3. These are OK:

    echo "This is a string with () characters"

    echo This is a string with \(\) characters

Is there a predefined function convert #2 to #3 in C?


Solution

  • Replacing all instances of ' with '\'' then enclosing the whole string in single quotes (') is one safe way. This works even with embedded newlines. Another method would be to insert \ before each character, except that then you have to do some special treatment for newlines since \ followed by a newline is ignored by the shell, not treated as a literal newline. You'd have to surround newlines with ' (single quotes).