How to escape special characters in a Bash string in Linux?

Posted on

The problem is with ssh that makes a quoted string to more than one if there are spaces. For example,

ssh user@host cmd "my string"

The cmd on host will be executed like

cmd my string

rather than

cmd "my string"

It will only work if the string is escaped like

ssh user@host cmd my string

Space is one example, there are many more other special characters in Bash.

The question is how to escape special characters in a Bash string in Linux nicely and easily?

The printf command line tool from GNU coreutils has an interpreted sequence %q that does escaping.

%q
  ARGUMENT is printed in a format that can be reused as shell input, 
  escaping non-printable characters with the proposed POSIX $'' syntax.

So, after escaping, the string can be well passed to bash -c for execution. An example is as follows.

$ function ac { echo $#; }; ac "hello world" new world
3

$ printf '%q' 'function ac { echo $#; }; ac "hello world" new world'
function\ ac\ \{\ echo\ \$#\;\ \}\;\ ac\ \"hello\ world\"\ new\ world

$ bash -c function\ ac\ \{\ echo\ \$#\;\ \}\;\ ac\ \"hello\ world\"\ new\ world
3

It can also be passed through ssh to execute on a remote host:

$ ssh localhost 'bash -c function\ ac\ \{\ echo\ \$#\;\ \}\;\ ac\ \"hello\ world\"\ new\ world'
3

Related Posts