Grep string with special character on remote server using ssh

Quoting and escaping over SSH is a PITA, so send the pattern to grep over a pipe:

$ echo '[email protected]' | ssh localhost grep -Ff - foo
Mar 29 18:15:06 mailserver amavis[12049]: (12049-13) Passed CLEAN {RelayedInbound}, [111.111.111.111]:25667 [111.111.111.111] <[email protected]> -> <[email protected]>,<[email protected]>, Queue-ID: 7711E18023F, Message-ID: <[email protected]>, mail_id: GQj-5bhH37Yi, Hits: -, size: 15551, queued_as: EE75C180429, 148 ms

Use the -F option so that grep doesn't treat it as a regex. The -f - option tells grep to read patterns from stdin.

Or quote and escape if you must:

$ ssh "grep '0e1430\[email protected]' bar"
Mar 29 18:15:06 mailserver amavis[12049]: (12049-13) Passed CLEAN {RelayedInbound}, [111.111.111.111]:25667 [111.111.111.111] <[email protected]> -> <[email protected]>,<[email protected]>, Queue-ID: 7711E18023F, Message-ID: <[email protected]>, mail_id: GQj-5bhH37Yi, Hits: -, size: 15551, queued_as: EE75C180429, 148 ms

In order to execute a grep command on the remote machine which holds the $ sign, you need:

  • Escape the $ using \
  • Escape the new \ using another \

i.e. adding \\ before the $ sign.

ssh -t root@remoteserver grep 0e1430\\[email protected] /root/log