Shell Scripting / Conditional Statements in Shell

Case Usage

This tutorial will cover how to use case statements in shell scripting. Case statements allow for a clean and organized way to test for multiple possible values of a variable or e…

Tutorial 2 of 4 4 resources in this section

Section overview

4 resources

Covers decision-making constructs in shell scripting using if-else, case, and test conditions.

Introduction

In this tutorial, we aim to provide a comprehensive and easy-to-understand guide on how to use case statements in shell scripting. Case statements are a powerful feature of shell scripting that allow you to test multiple possible values of a variable or expression in an organized and efficient manner.

By the end of this tutorial, you will learn how to:
- Understand and write case statements
- Use case statements effectively in your shell scripts

Prerequisites:
- Basic understanding of shell scripting
- Familiarity with shell command line

Step-by-Step Guide

One of the important concepts in shell scripting is conditional statements. They help in controlling the flow of execution of the script. One such conditional statement is case.

A case construct in shell scripting is similar to switch statement in C. It can be used to test simple values like integers and characters.

Here is the general form of a case statement:

case expression in
   pattern1)
      statements ;;
   pattern2)
      statements ;;
   *)
      statements ;;
esac

In the above structure, the case statement checks the expression against each pattern from the top to the bottom. Once a pattern matches, it executes the corresponding statements. The ;; indicates the end of each case. The * pattern will match anything if no other pattern matches.

Code Examples

Let's consider a practical example.

#! /bin/bash

echo "Enter a character:"
read char

case $char in
   [a-z])
      echo "You entered a lower case alphabet." ;;
   [A-Z])
      echo "You entered an upper case alphabet." ;;
   [0-9])
      echo "You entered a digit." ;;
   ?)
      echo "You entered a special character." ;;
   *)
      echo "Invalid input!" ;;
esac

In this script, we are reading a character from the user. The case statement then checks the character against each pattern. The first pattern [a-z] checks if the character is a lower case alphabet, and so on. The ? pattern checks for any single character.

If you run this script and input 'a', the output will be "You entered a lower case alphabet."

Summary

We covered how to use case statements in shell scripting, including writing case statements and understanding their flow of execution. The next step would be to practice using case statements in more complex scripts. You may also want to explore other types of conditional statements in shell scripting.

Practice Exercises

  1. Write a script that takes a day of the week (1-7) from the user and prints the corresponding day name (1 for Sunday, 2 for Monday, etc.). If the input is not between 1 and 7, print an error message.

  2. Modify the above script to use the day name instead of the day number. If the input is not a valid day name, print an error message.

Solutions

#! /bin/bash

echo "Enter a number (1-7):"
read day

case $day in
   1)
      echo "Sunday" ;;
   2)
      echo "Monday" ;;
   3)
      echo "Tuesday" ;;
   4)
      echo "Wednesday" ;;
   5)
      echo "Thursday" ;;
   6)
      echo "Friday" ;;
   7)
      echo "Saturday" ;;
   *)
      echo "Invalid input! Please enter a number between 1 and 7." ;;
esac
#! /bin/bash

echo "Enter a day:"
read day

case $day in
   "Sunday"|"sunday")
      echo "1" ;;
   "Monday"|"monday")
      echo "2" ;;
   "Tuesday"|"tuesday")
      echo "3" ;;
   "Wednesday"|"wednesday")
      echo "4" ;;
   "Thursday"|"thursday")
      echo "5" ;;
   "Friday"|"friday")
      echo "6" ;;
   "Saturday"|"saturday")
      echo "7" ;;
   *)
      echo "Invalid input! Please enter a valid day." ;;
esac

Remember, practice is key when it comes to mastering new concepts. Happy scripting!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help