module Shellwords

Defined in:

shellwords.cr

Constant Summary

SHELLSPLIT_REGEXP = /\G\s*(?>([^\s\\\'\"]+)|'([^\']*)'|"((?:[^\"\\]|\\.)*)"|(\\.?)|(\S))(\s|\z)?/m

Splits a string into an array of tokens in the same way the UNIX Bourne shell does.

argv = Shellwords.split('here are "two words"') argv #=> ["here", "are", "two words"]

Note, however, that this is not a command line parser. Shell metacharacters except for the single and double quotes and backslash are not treated as such.

argv = Shellwords.split('crystal my_prog.cr | less') argv #=> ["crystal", "my_prog.cr", "|", "less"]

String#shellsplit is a shortcut for this function.

argv = 'here are "two words"'.shellsplit argv #=> ["here", "are", "two words"]

Class Method Summary

Class Method Detail

def self.shellescape(str) #

Escapes a string so that it can be safely used in a Bourne shell command line. +str+ can be a non-string object that responds to +to_s+.

Note that a resulted string should be used unquoted and is not intended for use in double quotes nor in single quotes.

argv = Shellwords.escape("It's better to give than to receive") argv #=> "It\'s\ better\ to\ give\ than\ to\ receive"

String#shellescape is a shorthand for this function.

argv = "It's better to give than to receive".shellescape argv #=> "It\'s\ better\ to\ give\ than\ to\ receive"

Search files in lib for method definitions

pattern = "^[ \t]*def " open("| grep -Ern -e #{pattern.shellescape} lib") { |grep| grep.each_line { |line| file, lineno, matched_line = line.split(':', 3) # ... } }

It is the caller's responsibility to encode the string in the right encoding for the shell environment where this string is used.

Multibyte characters are treated as multibyte characters, not as bytes.

Returns an empty quoted String if +str+ has a length of zero.


[View source]
def self.shelljoin(array) #

Builds a command line string from an argument list, +array+.

All elements are joined into a single string with fields separated by a space, where each element is escaped for the Bourne shell and stringified using +to_s+.

ary = ["There's", "a", "time", "and", "place", "for", "everything"] argv = Shellwords.join(ary) argv #=> "There\'s a time and place for everything"

Array#shelljoin is a shortcut for this function.

ary = ["Don't", "rock", "the", "boat"] argv = ary.shelljoin argv #=> "Don\'t rock the boat"

You can also mix non-string objects in the elements as allowed in Array#join.

output = #{['ps', '-p', $$].shelljoin}


[View source]
def self.shellsplit(line) #

[View source]