Help us shape the future of Go! Take the 2026 Go Developer Survey

shellx

package
v0.29.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

Package shellx 提供 POSIX shell 的参数转义原语。

Quote 把任意字符串转义成**一个** shell word;QuoteArgv 把一组参数转义成 一条命令行。两者都是纯函数,不做策略判断——是否该拒绝某个输入由调用方 决定(换行、路径越界这类各有各的规则,见 pathx 与本包的文档)。

为什么需要它:把外部输入拼进 shell 命令时,不转义就等于把命令交给对方。 "a.txt; rm -rf /" 是**两条命令**而不是一个文件名;含空格的路径会被拆成 两个参数,于是文件被写到另一个地方——后者更隐蔽,因为命令看起来"成功"了。

转义方式用 POSIX 单引号:单引号内 shell 不做任何解释,所以唯一需要照顾的 是引号本身——关掉、转义、重新打开('\”)。这比反斜杠转义稳:反斜杠在 单引号内是字面量,双引号内又有一堆自己的规则,只有单引号是"里面什么都不 特殊"的。

空字符串是一个容易漏的边界:空参数仍然是一个参数,丢掉它会让 "cmd ” arg" 变成 "cmd arg",参数整体错位。所以 Quote("") 返回 "”"。

用法:

shellx.Quote("/tmp/a b.txt")   // "'/tmp/a b.txt'"
shellx.Quote("it's")            // "'it'\\''s'"
shellx.QuoteArgv("rm", "-f", p) // "rm '-f' '/tmp/x'" —— 逐个转义,程序名自己按需

与 pathx 的关系是两个不同的问题:pathx 问「这个路径合法吗」(越界即拒绝), shellx 问「这个字符串怎么写进命令行才不会被 shell 解释」。两者互补, 路径类输入通常两道都要过。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Quote

func Quote(s string) string

Quote quotes a string so that a POSIX shell passes it through as exactly one word, whatever it contains.

The result is always a single-quoted word. Nothing inside single quotes is special to the shell, so the only character that needs care is the quote itself: it is closed, escaped and reopened ("'\”"), which keeps the surrounding word intact.

An empty string becomes "”". An empty argument is still an argument, and dropping it would silently shift the whole command line: "cmd ” arg" must not become "cmd arg".

Quote does not decide what to do with a newline or a path that climbs out of its root -- it only escapes. Those are policy questions, and the caller is the one that knows them.

func QuoteArgv

func QuoteArgv(args ...string) string

QuoteArgv renders a command line from a list of arguments: every argument is quoted, and the results are joined with a single space.

The empty argument list renders as the empty string.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL