@suin/shell-escape-arg
    Preparing search index...

    Function default

    • Convert a string into a POSIX sh-safe single argument literal.

      Escapes a JavaScript string so it can be safely used as a single argument in POSIX-compatible shells (sh, bash, zsh, dash, etc.). The result, when parsed by the shell, produces exactly one argument with the original content.

      • Safe strings are returned as-is: Plain alphanumeric, Japanese, emoji, and other "harmless" Unicode characters pass through unchanged.
      • Unsafe strings are single-quoted: Wraps in '...' with internal ' escaped as '\'' (close, escaped quote, reopen).
      • Empty string (would disappear without quotes)
      • Contains Unicode whitespace (space, tab, newline, NBSP, ideographic space, etc.)
      • Contains ASCII control characters (U+0001–U+001F, U+007F)
      • Contains shell meta-characters: ' " \ $ \ | & ; < > ( ) * ? [ ] { } ! #`
      • Starts with ~ (prevents tilde expansion)
      • Single argument only: Does not build or format entire command lines.
      • POSIX shells only: Not for Windows cmd.exe or PowerShell.
      • Shell parsing safety only: Does not protect against program-level option interpretation (e.g., --dangerous-flag).

      Parameters

      • arg: string

        The string to escape for shell use.

      Returns string

      The escaped string, safe to use as a single shell argument.

      If arg is not a string.

      If arg contains NUL (\u0000), which POSIX arguments cannot include.

      // Safe strings pass through unchanged
      shellEscapeArg("abc") // "abc"
      shellEscapeArg("日本語") // "日本語"
      // Strings with spaces or special chars are quoted
      shellEscapeArg("a b") // "'a b'"
      shellEscapeArg("$HOME") // "'$HOME'"
      shellEscapeArg("*.txt") // "'*.txt'"
      // Single quotes are escaped with '\''
      shellEscapeArg("O'Reilly") // "'O'\\''Reilly'"
      // Empty string becomes ''
      shellEscapeArg("") // "''"
      // Leading tilde is quoted to prevent expansion
      shellEscapeArg("~user") // "'~user'"