esac
Marks the end of a case statement
TLDR
View documentation for the case keyword
SYNOPSIS
Since esac is a keyword and not a standalone command, its synopsis illustrates its usage within the case statement context.
case word in
pattern1) commands1 ;;
pattern2) commands2 ;;
...
esac
DESCRIPTION
esac is a reserved word in shell scripting, serving as the required closing keyword for the case statement. It marks the termination of a multi-way branching construct, allowing a script to execute different blocks of commands based on pattern matching against a given word or variable. Unlike external commands or shell built-ins, esac does not perform an action itself but defines the structural boundary of the case block. Its name, "esac," is "case" spelled backward, a common convention for closing keywords in the Bourne shell and its derivatives (e.g., if/fi). The case statement provides a clean and efficient way to handle multiple possible outcomes, offering an alternative to deeply nested if/elif structures when dealing with string or variable comparisons. Each block within a case statement typically ends with ;; to terminate the pattern's command list and prevent fall-through to the next pattern.
CAVEATS
esac is not an executable command. It must be paired with an opening case statement; otherwise, it will result in a syntax error. It cannot be used outside of a case block.
TYPE
esac is a shell reserved word, not an external command or a built-in function. It is interpreted directly by the shell's parser.
FUNCTIONALITY
It provides a clear and concise way to implement multi-way branching logic based on pattern matching, often leading to more readable scripts compared to complex nested if-elif-else structures for similar purposes.
HISTORY
The case/esac construct was introduced with the original Bourne Shell (sh) in Unix. Its design provided a structured way to handle multi-choice selections based on pattern matching, an improvement over deeply nested if/elif statements for such scenarios. The backward-spelled keyword esac (and fi for if) became a characteristic syntax feature of Bourne-style shells. It has been consistently adopted and standardized across all POSIX-compliant shells, including Bash, Zsh, Ksh, and Dash, ensuring its widespread and portable usage in shell scripting.