Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
eonil Avatar asked Sep 08 '10 14:09

eonil


3 Answers

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).

like image 56
R.. GitHub STOP HELPING ICE Avatar answered Nov 16 '22 01:11

R.. GitHub STOP HELPING ICE


There is no predefined function.

However, I believe it's sufficient to just enclose any shell argument in single quotes, and making sure that single quotes are escaped.

That's the logic of the escapeshellarg function in PHP and I believe it works reasonably well.

like image 34
Frerich Raabe Avatar answered Nov 16 '22 00:11

Frerich Raabe


Nothing pre-defined, and which characters need escaping depends on your shell. Look at the docs for your shell, and replace each X with \X. Using double quotes " will require the same treatment if the string you're enclosing contains a ".

Also note that this will get more complicated if you intend to encapsulate more complicated expressions (anything compounded with a ';', for example)

like image 41
jkerian Avatar answered Nov 16 '22 00:11

jkerian