Linux Shell Scripting: Case Statement

Linux Shell Scripting: Case Statement

What is Shell Scripting?

Shell scripting refers to writing scripts or programs that are interpreted and executed by a shell, which is a command-line interpreter for operating systems like Unix, Linux, and macOS. The shell is an interface between the user and the operating system, allowing users to execute commands and perform various tasks.

A shell script is a text file containing a series of commands written in a scripting language specific to the shell being used, such as Bash (Bourne Again SHell) or C Shell (csh). These scripts can automate repetitive tasks, perform system administration tasks, or combine multiple commands into a single script for more complex operations.

Case Statement

In Linux shell scripting, a case statement is a control structure used for conditional branching based on patterns or values. It provides a way to compare a variable or expression against a series of patterns and execute different blocks of code based on the match.

Here's a breakdown of how a case statement works:

  1. The expression is evaluated, which is typically a variable or an expression that you want to compare against the patterns.

  2. The in keyword marks the beginning of the list of patterns to match.

  3. Each pattern represents a condition to match against the expression. It can include wildcards, such as * for any string or ? for any single character, and regular expressions can also be used for pattern matching.

  4. The code block following each pattern is executed when the corresponding pattern matches the expression. It should be enclosed within parentheses ( and ) or terminated with ;;.

  5. If no pattern matches the expression, the code block following *) is executed as the default case.

  6. The esac keyword marks the end of the case statement.

Creating Shell Script

  • Create a file using the command touch.

  • Use the file extension (.sh).

  • To edit the file use the command vi with file name.

  • Write the shebang at the top.

  • The syntax we use is the case with the special variable.($1).

  • in will start the case.

  • The first case we are checking here is the bye.

  • We used the (*) case at the end because if any argument doesn't match the cases it will echo the 'Huh?'.

  • We will close the case by writing esac at the end.

  • Use the bash command with the file name to Run the Shell Script.

  • Below you can see the results with different arguments.