"Mark A. Hershberger" <m...@nichework.com> writes: > Is there a piece of standard code or a library that I can use to escape > a string so it is safe to pass to bash? > > Specifically, I have submitted this bit[1] to add deletion of duplicate > messages to a guile script included with mu (maildir utils) and now > we're looking at how to escape the file names to keep this maliciously > inserted maildir files from causing problems. > > Any hints? > > > Footnotes: > [1] https://github.com/djcb/mu/pull/593
I don't know if we already have something for this, but it's very simple for POSIX sh, and bash: Replace all occurrences of ' (single-quote) with '\'' (single-quote, backslash, single-quote, single-quote), then prepend and append a pair of ' (single-quote) to it. So e.g. foo'baz becomes: 'foo'\''baz' That is guaranteed to be parsed as one token SO LONG as it's separated by white-space from other things, and no ${} or $() or such will be interpreted. Explanation: in POSIX sh syntax, absolutely no characters have special meaning within single-quotes, except for the terminating single-quote. I.e. one can not even use \' to represent a literal single-quote inside a single-quoted string. What 'foo'\''bar' does is close a single-quoted string, insert a bare backslash-escaped single-quote, then reopen the single-quoted string and continue. Taylan