[Linux basics and shell script] case process control statement

1. Basic syntax of case statement

1.1 How the case statement works

In Shell scripts, the case statement is a multiple-way selection structure that allows different operations to be performed when a variable is equal to multiple values. The case statement casestarts with the keyword and ends with esacthe (reverse case) keyword.

1.2 Basic case statements

Here is an example of a basic case statement:

case $variable in
   pattern1)
      command1
      command2
      ;;
   pattern2)
      command3
      command4
      ;;
esac

In this example, $variableare the variables we want to check, pattern1and pattern2are the patterns we want to match, command1, command2, command3and command4are the commands we want to execute if the match is successful. ;;Used to indicate the end of a pattern.

1.3 Case statements using wildcards

In the case statement, we can also use the wildcard character (*) to match any character. Here is an example of a case statement using wildcards:

case $variable in
   *.txt)
      echo "This is a text file."
      ;;
   *.jpg|*.png)
      echo "This is an image file."
      ;;
   *)
      echo "Unknown file type."
      ;;
esac

In this example, we *.txt're matching all text files, *.jpg|*.pngwe're matching all JPG and PNG images, *and we're matching all other file types.

2. Uses and advantages of case statements

2.1 case statement is used in multiple selection scenarios

In shell scripts, case statements are very useful when there are many possible options and different actions need to be performed based on these options. For example, in an interactive script, we can use case statements to handle user input:

echo "Enter your choice: "
read choice

case $choice in
   1)
      echo "You chose option 1."
      ;;
   2)
      echo "You chose option 2."
      ;;
   *)
      echo "Invalid option."
      ;;
esac

2.2 Case statements are used for pattern matching

Another important application of case statements is pattern matching. As mentioned earlier, we can use wildcards to match multiple patterns. This is especially useful when working with files, for example we can perform different operations based on the file extension:

file="example.txt"

case $file in
   *.txt)
      echo "This is a text file."
      ;;
   *.jpg)
      echo "This is a JPG file."
      ;;
   *)
      echo "Unknown file type."
      ;;
esac

2.3 Advantages of case statement compared to if-elif-else

One of the main advantages of the case statement over the if-elif-else structure is that it is clearer and more intuitive. When there are many possible options, using case statements can make the code more readable and easier to maintain. In addition, because the case statement checks each pattern one by one in order, it is usually more efficient than the if-elif-else structure.

3. Application examples of case statements

3.1 Example 1: Processing user input

In this simple example, we will use case statements to handle user input. The patterns we use are [yY] | [yY][eE][sS]and [nN] | [nN][oO], which means that whether the user enters 'yes' or 'no' in uppercase or lowercase, our script will handle it correctly.

echo "Please enter yes or no: "
read answer

case $answer in
   [yY] | [yY][eE][sS])
      echo "You answered YES."
      ;;
   [nN] | [nN][oO])
      echo "You answered NO."
      ;;
   *)
      echo "Invalid input."
      ;;
esac

3.2 Example 2: Processing command line parameters

In this example, we will use a case statement to handle the command line parameters of the script. $1Represents the first parameter of the script. Depending on the value of this parameter, we perform different operations.

case $1 in
   start)
      echo "Starting the service..."
      ;;
   stop)
      echo "Stopping the service..."
      ;;
   restart)
      echo "Restarting the service..."
      ;;
   *)
      echo "Invalid command. Please use start, stop, or restart."
      ;;
esac

3.3 Example 3: Using case statements to write menus

In this example, we will create a simple menu using case statements. Depending on the user's input, we perform different actions.

echo "1. Start"
echo "2. Stop"
echo "3. Restart"
echo "Please enter your choice: "
read choice

case $choice in
   1)
      echo "Starting..."
      ;;
   2)
      echo "Stopping..."
      ;;
   3)
      echo "Restarting..."
      ;;
   *)
      echo "Invalid choice."
      ;;
esac

3.4 Example 4: Perform operations based on file type

In this example, we will use case statements to perform different operations based on the file type. We determine the type of file by checking its extension.

file="example.txt"

case $file in
   *.txt)
      echo "Opening the text file..."
      ;;
   *.jpg)
      echo "Opening the JPG file..."
      ;;
   *.png)
      echo "Opening the PNG file..."
      ;;
   *)
      echo "Unknown file type."
      ;;
esac

3.5 Example 5: Processing system signals

In this example, we will use case statements to handle signals sent by the system. When our script receives SIGINTthe or SIGTERMsignal, we print a corresponding message.

trap 'case $1 in
   SIGINT)
      echo "You pressed Ctrl+C!"
      ;;
   SIGTERM)
      echo "Terminating the script..."
      exit 1
      ;;
   esac' SIGINT SIGTERM

3.6 Example 6: Processing file extensions

In this example, we will use a case statement to handle the file extension. We iterate through all the files in the current directory and perform different operations based on the file extension.

for file in *
do
   case $file in
      *.txt)
         echo "$file is a text file."
         ;;
      *.docx)
         echo "$file is a Word document."
         ;;
      *.jpg)
         echo "$file is a JPG image."
         ;;
      *.png)
         echo "$file is a PNG image."
         ;;
      *)
         echo "$file is an unknown type."
         ;;
   esac
done

3.7 Example 7: Script option processing

In this example, we will use case statements to handle the script's options. getoptsThe function is used to process command line options, and $optthe variable stores the current option character.

while getopts ":a:b:c" opt; do
  case $opt in
    a) a_arg="$OPTARG"
    ;;
    b) b_arg="$OPTARG"
    ;;
    c) c_arg=1
    ;;
   

\?) echo "Invalid option -$OPTARG" >&2
    ;;
  esac
done

3.8 Example 8: Creating a backup of a file

In this example, we will use a case statement to create a backup based on the modification time of the file. $(date +%m -r $file)We can get the last modified month of the file, and then we copy the file to the corresponding directory based on the month.

for file in *
do
   case $(date +%m -r $file) in
      01|02|03)
         mkdir -p Q1
         cp $file Q1/
         ;;
      04|05|06)
         mkdir -p Q2
         cp $file Q2/
         ;;
      07|08|09)
         mkdir -p Q3
         cp $file Q3/
         ;;
      10|11|12)
         mkdir -p Q4
         cp $file Q4/
         ;;
   esac
done

3.9 Example 9: Processing system logs

In this example, we will use case statements to process the system's log files. We first use grepthe command to extract the lines containing 'error' from the system log, and then use the case statement to print different messages according to the type of error.

grep 'error' /var/log/syslog | while read errorline
do
   case $errorline in
      *network*)
         echo "Network error: $errorline"
         ;;
      *disk*)
         echo "Disk error: $errorline"
         ;;
      *)
         echo "Unknown error: $errorline"
         ;;
   esac
done

3.10 Example 10: Simulating state machine

In this example, we will simulate a state machine using case statements. We have a variable stateand depending on its value we perform different operations and update its value.

state="start"

while true
do
   case $state in
      start)
         echo "Starting..."
         state="run"
         ;;
      run)
         echo "Running..."
         state="stop"
         ;;
      stop)
         echo "Stopping..."
         state="start"
         ;;
   esac
done

Guess you like

Origin blog.csdn.net/weixin_52665939/article/details/131609447