Skip to contents

shell_quote() quotes strings with base::shQuote() but only if they contain characters that may need quoting when passed to a shell. rscript_filename() uses it by default to quote the script file name. It is useful if you set the prog argument of OptionParser() to a file name that may contain spaces or other special characters.

Usage

shell_quote(x, type = c("sh", "csh", "cmd", "cmd2"))

Arguments

x

A character vector.

type

The type of shell quoting passed on to base::shQuote(). The default is "sh" unless on Windows in a shell other than Git Bash, MSYS2, or Cygwin (detected via the MSYSTEM and SHELL environment variables) in which case it is "cmd". Unlike base::shQuote() this means Git Bash, MSYS2, and Cygwin users on Windows get "sh" quoting.

Value

A character vector the same length as x.

Details

Which strings are left as is depends on type:

  • "sh" and "csh": strings that only contain ASCII letters, digits, and the characters _, @, %, +, :, ,, ., /, and - as well as = unless it is the first character or the string starts with a shell variable assignment (e.g. a=b.R).

  • "cmd": strings that only contain ASCII letters, digits, and the characters _, %, +, :, ., /, \, and -. Quoting does not stop cmd.exe from expanding % so there is no benefit to quoting it.

  • "cmd2": strings that don't contain any of the characters base::shQuote() escapes for this type i.e. (, ), %, !, ^, ", <, >, &, and |.

Missing values are left as is. Empty strings are quoted unless type is "cmd2". Each string is quoted independently of the others.

Note

Quoting aims to make file names safe to copy and paste into an interactive shell but some unusual file names still break (all of them would also break if left unquoted):

  • "sh": names with both ' and ! in bash and zsh (history expansion), names with both ' and a backtick in fish, and names with two consecutive backslashes in fish (which collapses them).

  • "sh" and "csh": names with ! or a newline in csh and tcsh, as well as names with both ' and any of $, a backtick, ", or \ in csh and tcsh when type is "sh".

  • "cmd": names with % in cmd.exe (expanded even within double quotes) and names with $ or a backtick in PowerShell.

The default type is also a heuristic: for example cmd.exe started from within Git Bash inherits MSYSTEM and so gets "sh" quoting.

See also

base::shQuote() which always quotes its input and rscript_filename().

Examples

shell_quote(c("script.R", "my script.R"))
#> [1] "script.R"      "'my script.R'"
shell_quote(c("C:\\dir\\script.R", "C:\\my dir\\script.R"), type = "cmd")
#> [1] "C:\\dir\\script.R"        "\"C:\\my dir\\script.R\""