Linux Bash Case Statement with Examples

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/linux-bash-case-statement-with-examples/
PINTEREST
PINTEREST
INSTAGRAM

Bash provides an interactive shell and programming environment for its users. Programming environment have very reach features like loops for and while, selection if and case. In this tutorial we will examine the case mechanism in detail.

Syntax

Syntax of case statement is a bit different and complex then if and other conditional expressions. case statement generally uses expression which is value we want to check and patterns which is a case.

  • EXPRESSION is the value we want to evaluate.
  • PATTERN1 one of the situation we want to check
  • PATTERN2 is another situation we want to check
  • ... means we can add more situations like PATTERN1 and PATTERN2 .
  • STATEMENTS is the code we want to execute when the situation meets.
  • esac is the end of case statement.

Check Current User Example

In this example we will check the current user and print the user name to the screen. In this example we will use $(whoami) which will return current user name and check with "ismail") and "root") conditions. If one of them matches we will print with echo "You are ...";; line. Keep in mind that ;; specifies end of current condition.

Check Current User Example
Check Current User Example

Check Given Input

We can get input from the user and use it in a case . In this example we will get current user age from command line as input and then print some sentence according to input age.

LEARN MORE  Bash If , Else If Conditionals

Check Given Input
Check Given Input

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/linux-bash-case-statement-with-examples/
PINTEREST
PINTEREST
INSTAGRAM