Search code examples
bashdialogwhiptail

How to quote variables in a whiptail command with dynamic/conditional options?


I need to disable options in a dialog command built in a Bash script. Here is the original working script:

my_backtitle="This is a test"
selected_options=($(dialog \
    --backtitle "$my_backtitle" \
    --separate-output \
    --checklist "Select your options:" 0 0 \
    "option1" "description of option 1" "" \
    "option2" "description of option 2" "" \
    3>&1 1>&2 2>&3))

Then I get selected options directly in the array.

In some cases I need to disable some of the options. I've tried this way:

my_condition=false
my_backtitle="This is a test"
dialog_parameters="--backtitle '"
dialog_parameters+="$my_backtitle"
dialog_parameters+="' --separate-output \
    --checklist "Select your options:" 0 0 "
if $my_condition
then
    dialog_command+="'option1' 'description of option 1' '' "
fi
dialog_command+="'option2' 'description of option 2' ''"
selected_options=($(dialog $dialog_parameters 3>&1 1>&2 2>&3))

But I get the error: Error: Unknown option is.

With the debugging set -e parameter, I see the dialog command after parameters expansion: dialog --backtitle ''\''this' is a 'test'\''' --separate....

How can I quote correctly a string containing spaces in that case?

I've tried by using \" around the variable, and I also tried storing parameters in an array of strings, but It did not solve the problem.

How should I write such a parametrized dialog command?


Solution

  • You need to use an array, not a string, to hold individual arguments that may themselves contain whitespace.

    my_condition=false
    my_backtitle="This is a test"
    args=(--backtitle "$my_backtitle")
    args+=(--separate-output)
    args+=(--checklist "Select your options:" 0 0)
    if $my_condition
    then
        args+=( "option1" "description of option 1" )
    fi
    args+=('option2' 'description of option 2')
    selected_options=($(dialog "${args[@]}" 3>&1 1>&2 2>&3))