case - Linux


Overview

The case command in Linux is not a standalone utility but a shell built-in that is used to execute commands based on specific conditions. It is primarily used for matching string values against patterns and executing code blocks depending on the match. It is an effective tool for conditional scripting within bash or other POSIX-compliant shells.

Syntax

The case statement has the following syntax:

case word in
  pattern1)
    commands1;;
  pattern2)
    commands2;;
  ...
  patternN)
    commandsN;;
  *)
    default_commands;;
esac
  • word: The variable or string being matched against the patterns.
  • pattern: A pattern against which the value of word is tested. Patterns are compatible with glob pattern matching used in filename expansion.
  • commands: Commands that are executed if word matches the corresponding pattern.
  • *): An optional catch-all pattern that matches anything if no other pattern matches.
  • ;;: Terminates a pattern block, indicating the end of the branch.
  • esac: Ends the case statement, and is case spelled backwards.

Options/Flags

The case statement does not have options or flags. Its behavior entirely depends on the patterns and the commands specified in its syntax.

Examples

  1. Simple Example:

    case $1 in
      start)
        echo "Starting the process";;
      stop)
        echo "Stopping the process";;
      *)
        echo "Usage: $0 {start|stop}";;
    esac
    
  2. Complex Example:

    case $file_extension in
      jpg|jpeg)
        echo "File is an image";;
      txt|doc)
        echo "File is a text document";;
      *)
        echo "Unsupported file format";;
    esac
    

Common Issues

  • Pattern Not Matching: Ensure that your patterns correctly match the expected string values. Remember that patterns use glob matching rules.
  • Forgetting ;;: Each pattern block must end with ;;, or it will result in a syntax error.

Integration

The case statement can be combined with loops and other shell commands to create more complex scripts. For example:

for filename in *.txt; do
  case $filename in
    letter_*)
      mv "$filename" letters/;;
    report_*)
      mv "$filename" reports/;;
    *)
      echo "Unknown file type: $filename";;
  esac
done
  • if/else: Another conditional statement tool used for decision-making in shells.
  • select: A shell command for creating simple menus, useful with case for handling user choices.

For more complex scripting or decision-making tasks, consider learning more about these related commands, or explore shell scripting tutorials to see case statements in broader contexts.