Skip to main content

escape_command_for_shell

Function escape_command_for_shell 

Source
pub fn escape_command_for_shell(command: &str) -> String
Expand description

Escape a command for safe execution in shell (for pkill -f patterns)

This escapes characters that could cause shell injection when used inside single-quoted shell strings (like in pkill -f 'command').

Escaped characters:

  • Single quotes: ''"'"'
  • Dollar signs: $\$ (prevents variable expansion)
  • Backticks: ` → ``` (prevents command substitution)
  • Backslashes: \\\ (prevents escape sequences)
  • Parentheses: ( and )\( and \) (prevents subshells)
  • Pipes: |\| (prevents command chaining)

§Example

use ssh_mcp::ssh::sanitize::escape_command_for_shell;

let escaped = escape_command_for_shell("echo 'hello' | cat");
assert_eq!(escaped, "echo '\"'\"'hello'\"'\"' \\| cat");