Search code examples
bashdouble-quotes

Shell script with error output using && or ||


I'm writing a bash code in which I’d like the user to select a folder using zenity. The problem is that if the folder name has some spaces in its name, the selection will fail, but the script will continue (what I don't want). That is why I tried something to tell the user that something went wrong before exiting the script.

inputStr=$(zenity --file-selection --directory "${HOME}")
cd $inputStr || zenity --error --width=300 --height=100 --text "The folder name must not contain spaces." && exit

That works when the selection fails. But the fact is that it also exits the script when the selection is fine. I tried replacing «&&» with «||» because I thought I misunderstood something, but that way it runs the code whether the selection fails or not.

Does someone have an idea ?


Solution

  • In shell, || and && have equal precedence and are evaluated from left to right in a single list. You are expecting it to be parsed and evaluated as cd $inputstr || (zenity ... && exit), but it's really being evaluated as (cd $inputstr || zenity ...) && exit. Thus, your script exits as long as either cd or zenity succeeds, rather than calling zenity and exiting if the cd fails.

    You probably also want to exit even if zenity, for any reason, fails: use ;, not &&.

    Never mix && and || in the same list. Instead, use a proper if statement.

    if ! cd "$inputstr"; then
        zenity ...
        exit
    fi