tech-userlevel archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: Proposal to add /usr/bin/shquote



On Sat, 06 Sep 2008, David Laight wrote:
> > I often find the need, in shell scripts, to escape arguments to be
> > passed to other shell commands.  I'd like to add a /usr/bin/shquote
> > command as a simple wrapper around shquotev(3) to do this.
>
> I don't see the problem ?
> You just need to understand when the shell does 'field splitting'.

The underlying problem is that the shell doesn't have a "list of
strings" data type, except in the special case of "$@". Scripts that
want lists of strings have to simulate them somehow by storing the
entire list in a single shell variable; most such scripts use space,
colon, or comma, as separators within the list variable, but they fail
if the individual items themselves contain that separator.

For example, here's some broken code that simulates a list of file names
by separating the names with spaces; it doesn't work properly if "$@"
contains file names with embedded spaces:

    file_list=""
    for file in "$@"; do
            if [ -e "$file" ]; then
                    file_list="${file_list}${file_list:+ }${file}"
            else
                    echo "${file} does not exist, ignoring it"
            fi
    done
    ls -l "${file_list}" # wrong, all names combined into a single arg
    ls -l ${file_list}   # wrong, names with embedded spaces will be split

and here's the corresponding working code, using a combination of shquote
and eval:

    file_list=""
    for file in "$@"; do
            if [ -e "$file" ]; then
                    file_list="${file_list}${file_list:+ }$( \
                                    shquote -- "${file}" )"
            else
                    echo "${file} does not exist"
            fi
    done
    eval "ls -l ${file_list}"

--apb (Alan Barrett)


Home | Main Index | Thread Index | Old Index