0

I am writing a script that opens a bunch of programs. However, sometimes I only want some of the programs open, so I am using zenity question dialogs to ask whether it should open each program.

    zenity --question --text "Start Firefox?"
    start_firefox=$?
    if [[ $start_firefox -eq 1 ]]; then
        # opens Firefox...
    fi
    zenity --question --text "Open Dolphin?"
    open_dolphin=$?
    if [[ $open_dolphin -eq 0 ]]; then
        directory=$(zenity --file-selection --directory)
        # continues to open Dolphin...
    fi
    zenity --question --text "Open gedit?"
    open_gedit=$?
    if [[ $open_gedit -eq 0 ]]; then
        # opens gedit...
    fi

The problem here is if I click on No on any of the questions, or Cancel on the file selector, it exits the entire script and I can't even collect the return value of the zenity dialog. The same code works just fine if I type it in a bash shell.

Zenul_Abidin
  • 573
  • 8
  • 23

1 Answers1

0

I had to type the command set +e before I opened any zenity dialog boxes. This is because a bash script exits when a command returns a non-zero exit code, which it sees as failed. A zenity question returns 0 if the user clicked yes and 1 if the user clicked no. Since 1 is a non-zero exit code, bash thought the command failed, and terminated the entire script.

What the command above does is don't stop the script on any non-zero exit status, which has the side effect that other commands that fail won't exit the script either, so use with care.

Also see the question Automatic exit from bash shell script on error.

Zenul_Abidin
  • 573
  • 8
  • 23
  • "*`The default behavior of bash is set -e`*". I don't think so. Do you have any sources that state `set -e` is the default? – Socowi Dec 09 '19 at 12:07
  • @Socowi Since the bash infopage didn't say anything about this, I looked that the bash [sources](https://github.com/bminor/bash/search?q=errexit_flag&unscoped_q=errexit_flag) and in fact, I discovered that this is *not* the default. – Zenul_Abidin Dec 09 '19 at 12:27
  • @Zenul_Abidin : You can see which options are in effect, by doing a `echo $-`. Unless you have set `-e` explicitly (for instance in your .bashrc), `e` won't be in the list. – user1934428 Dec 09 '19 at 12:31