Search code examples
bashshellcygwin

How to call command with double and single quotes in Bash


I've been trying to write shell scripts for IBM License Use Management. Scripts will run on Cygwin/Windows. Some arguments (those containing spaces in particular) need to be passed with both double and single quotes. The following works in the commandline and also as a complete command in the script:

i4blt -Al -v "'Dassault Systemes'" -p "PR1 VER123"

But the same would not work when I try the vendor name argument as a variable, i.e. VENDOR="\"'Dassault Systemes'\"" or anything like that. So the following:

VENDOR="\"'Dassault Systemes'\""
PRODUCT="\"PR1 VER123\""
i4blt -Al -v $VENDOR -p $PRODUCT

returns this:

Vendor "'Dassault not found

I tried escaping the quotes, passing as arguments to a function, and many more solution candidates from Stackoverflow. The program I'm trying to run from the script (i4blt) insists on evaluating only the first part of the variable, until the space. Ideas appreciated.


Solution

  • When you run i4blt with variables, they will be expanded into their values, including their spaces, and Bash will split the arguments by spaces.

    Thus

    VENDOR="\"'Dassault Systemes'\""
    PRODUCT="\"PR1 VER123\""
    i4blt -Al -v $VENDOR -p $PRODUCT
    

    Will run i4blt with the following arguments:

    1. -Al
    2. -v
    3. "'Dassault
    4. Systemes'"
    5. -p
    6. "PR1
    7. VER123"

    (Including the quotes, since that's how the variables were set.)

    To make each expanded variable a single argument, you need to quote it:

    i4blt -Al -v "$VENDOR" -p "$PRODUCT"
    

    The arguments will then be:

    1. -Al
    2. -v
    3. "'Dassault Systemes'"
    4. -p
    5. "PR1 VER123"

    (Once again including the quotes.)