Skip to content

shlex

Shell quoting and word splitting.

The quoting these functions produce is POSIX shell quoting, suitable for a command line handed to sh. It is not the right escaping for a Windows command line, nor for running a program directly, as run does -- arguments passed that way need no quoting at all.

Functions

join iterable -> Str

Joins values into a single POSIX shell command line, quoting each.

Parameters

NameTypeDescription
iterable Iterable[Value] Values, each converted to a string as std.verbatim would.

Errors

Exception Condition
RuntimeError A value contains a NUL byte

Example

assert_eq (join ["echo", "hello world"]) "echo 'hello world'"

quote obj -> Str

Quotes a value for use as a single POSIX shell word.

The result is a string the shell expands back to exactly obj, quoted only when quoting is needed.

Parameters

NameTypeDescription
obj Value Value to quote, converted to a string as std.verbatim would.

Errors

Exception Condition
RuntimeError The value contains a NUL byte, which no shell word can carry

Example

assert_eq (quote "hello world") "'hello world'"
assert_eq (quote plain) plain

split string -> Iter[Str]

Splits a POSIX shell command line into words, undoing quoting.

The split is lazy: a malformed line, such as one with an unterminated quote, is not diagnosed when split returns but when iteration reaches the end of the input.

Parameters

NameTypeDescription
string Str Command line to split.

Errors

Exception Condition
TypeError string is not a Str
RuntimeError Raised during iteration if the line is malformed

Example

for arg = split "echo 'hello world'"
  echo $arg
# echo
# hello world