LeonidMew
LeonidMew

Reputation: 502

Case statement not working in bash, conditions not apply

Case statement not working. Pressing Enter(empty string) not make script exit, other cases not working too. No one exit 1 commands run when it should, all cases fails when I type text specially for it.

I find out what case works, but exit 1 statement in it not exits the script. How to exit script in that place correctly?

#!/bin/bash
...
get_virtual_host() {
    if [ -t 0 ]; then
        read -p "Create virtualhost (= Folder name,case sensitive)" -r host
    else
        # same as 'read' but for GUI
        host=$(zenity --forms --add-entry=Name --text='Create virtualhost (= Folder name,case sensitive)')
    fi
    case "$host" in
        "")            notify_user "Bad input: empty" ;      exit 1 ;;
        *"*"*)         notify_user "Bad input: wildcard" ;   exit 1 ;;
        *[[:space:]]*) notify_user "Bad input: whitespace" ; exit 1 ;;
    esac
    echo "$host"
}

host=$(get_virtual_host)

Addition to clarify:

notify_user () {
    echo "$1" >&2
    [ -t 0 ] || if type -p notify-send >/dev/null; then notify-send "$1"; else xmessage -buttons Ok:0 -nearmouse "$1" -timeout 10; fi
}

Upvotes: 1

Views: 1405

Answers (1)

John Kugelman
John Kugelman

Reputation: 361605

The function is in fact written correctly. It's how it's called that's the problem.

host=$(get_virtual_host)

When you capture a command's output the command runs in a subshell. Exiting the subshell doesn't directly cause the parent shell to exit; the parent shell needs to check the subshell's exit status.

host=$(get_virtual_host) || exit

This will exit the parent if get_virtual_host fails. A bare exit without an explicit exit code forwards the existing value of $?.

Upvotes: 3

Related Questions