A system administrator is writing a bash script to manage a service. The script must accept a single argument-start, stop, restart, or status-and execute a corresponding, separate function for each. If an invalid argument is supplied, it should print a usage message.
Which of the following conditional constructs is the most idiomatic and efficient for this scenario?
The correct answer is the case statement. For shell scripts that need to take different actions based on a single variable matching one of several different string patterns, the case statement is the most efficient and readable construct. It is considered more idiomatic for this specific task, such as in init scripts, than a long series of if/elif tests.
The if/elif/else structure is functional but less efficient, as it may require multiple separate evaluations. The for loop is the incorrect type of control structure for this task, as it is designed for iteration, not conditional branching on a single value. The if statement with -o (OR) operators is logically flawed because it cannot be used to select one of several mutually exclusive actions.
Ask Bash
Bash is our AI bot, trained to help you pass your exam. AI Generated Content may display inaccurate information, always double-check anything important.
What are the advantages of using a `case` statement over `if`/`elif`/`else` in bash scripting?
Open an interactive chat with Bash
What happens if a `case` statement in bash does not match any pattern?
Open an interactive chat with Bash
What is the syntax of a `case` statement in bash scripting?
Open an interactive chat with Bash
CompTIA Linux+ XK0-006 (V8)
Automation, Orchestration, and Scripting
Your Score:
Report Issue
Bash, the Crucial Exams Chat Bot
AI Bot
Loading...
Loading...
Loading...
IT & Cybersecurity Package Join Premium for Full Access