module Shellwords

Manipulates strings like the UNIX Bourne shell

This module manipulates strings according to the word parsing rules of the UNIX Bourne shell.

The shellwords() function was originally a port of shellwords.pl, but modified to conform to the Shell & Utilities volume of the IEEE Std 1003.1-2008, 2016 Edition

Usage

You can use Shellwords to parse a string into a Bourne shell friendly Array.

require 'shellwords'

argv = Shellwords.split('three blind "mice"')
argv #=> ["three", "blind", "mice"]

Once you’ve required Shellwords, you can use the split alias String#shellsplit.

argv = "see how they run".shellsplit
argv #=> ["see", "how", "they", "run"]

They treat quotes as special characters, so an unmatched quote will cause an ArgumentError.

argv = "they all ran after the farmer's wife".shellsplit
     #=> ArgumentError: Unmatched quote: ...

Shellwords also provides methods that do the opposite. Shellwords.escape, or its alias, String#shellescape, escapes shell metacharacters in a string for use in a command line.

filename = "special's.txt"

system("cat -- #{filename.shellescape}")
# runs "cat -- special\\'s.txt"

Note the ‘–’. Without it, cat(1) will treat the following argument as a command line option if it starts with ‘-’. It is guaranteed that Shellwords.escape converts a string to a form that a Bourne shell will parse back to the original string, but it is the programmer’s responsibility to make sure that passing an arbitrary argument to a command does no harm.

Shellwords also comes with a core extension for Array, Array#shelljoin.

dir = "Funny GIFs"
argv = %W[ls -lta -- #{dir}]
system(argv.shelljoin + " | less")
# runs "ls -lta -- Funny\\ GIFs | less"

You can use this method to build a complete command line out of an array of arguments.

Authors

Contact