Hacker News new | past | comments | ask | show | jobs | submit login

There is no excuse for shell escaping bugs like this. 100% safe and reliable shell escaping is trivial:

s/'/'\''/g

s/^/'/

s/$/'/




Can you provide a demonstration for why this is adequate? It seems like it might still possible to get single quotes in the input to be interpreted by the shell by putting a backslash in the input.


See the man page for a POSIX-compliant shell, like dash[0], and find the section on single-quoted strings. For example:

> Enclosing characters in single quotes preserves the literal meaning of all the characters (except single quotes, making it impossible to put single-quotes in a single-quoted string).

Note also the following examples, with double-quoted strings:

  $ echo a b c
  a b c
  $ echo "a" "b" "c"
  a b c
  $ echo "a""b""c"
  abc
  $ echo "a" b "c"
  a b c
  $ echo "a"b"c"
  abc
The same concatenation rules apply to single-quoted strings. So, by putting single quotes at the beginning and end of a string, you only need to worry about single quotes within the string. You can "escape" those with '\'', where the first single quote terminates the preceding single-quoted string, the backslash+single-quote pair is a literal unquoted/escaped single quote in the shell, and the final single quote begins single-quoting again for the rest of the string. The three parts are then dequoted and concatenated together back into your original string by the shell.

http://linux.die.net/man/1/dash


I knew about the concatenation rules, but I was missing the fact that backslash does nothing in single-quoted strings.

  $ echo 'hi\'
  hi\


The shell doesn't interpret double-backslash in a single-quoted string. Therefore, this will indeed do.




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: