Bash Script Programming:
Case statement:
Multi-Branch If statement:
if CONDITION1; Then
Branch 1
Elif CONDITION2; Then
Branch 2
...
else CONDITION; Then
Branch N
Fi
Example 1: Display a menu to the user;
CPU) Display CPU information
MEM) Display Memory information
Disk) Display disks information
Quit) quit
Requirements: (1) Prompt the user to give their own choice;
(2) The correct choice will give the corresponding information; otherwise, prompt to re-select the correct option;
#!/bin/bash
#
Cat << EOF
CPU) Display CPU information
MEM) Display Memory infomation
Disk) Display disks information
Quit) quit
===============================
Eof
Read-p "Enter your option:" option
While ["$option"! = "CPU"-a "$option"! = "Mem"-a "$option"! = "Disk"-a "$option"! = "Quit"]; Do
echo "CPU, mem, disk, quit"
Read-p "Enter your option again:" option
Done
If ["$option" = = "CPU"]; Then
Lscpu
elif ["$option" = = "mem"]; Then
Free-m
elif ["$option" = = "Disk"]; Then
Fdisk-l/dev/[hs]d[a-z]
Else
echo "Quit"
Exit 0
Fi
Syntax format for Case statements:
Case $VARAIBLE in
PAT1)
Branch 1
;;
PAT2)
Branch 2
;;
...
*)
Branch N
;;
Esac
Case supports GLOB-style wildcard characters:
*: Any character of any length;
?: any single character;
[]: Any single character in the range;
A|b:a or B;
Example: Write a service framework script;
$lockfile, Value/var/lock/subsys/script_name
(1) This script can accept start, stop, restart, status of one of the four parameters;
(2) If the parameter is not four, then the use of help after the exit;
(3) Start, create Lockfile, and show start, stop, delete lockfile, and display stop, restart, delete this file before you create this file, and then display the restart complete; status, if Lockfile exists, The running is displayed, otherwise, it is displayed as stopped.
#!/bin/bash
#
# Chkconfig:-50 50
# description:test Service Script
#
prog=$ (basename)
lockfile=/var/lock/subsys/$prog
Case $ in
Start
If [-f $lockfile]; Then
echo "$prog is running yet."
Else
Touch $lockfile
[$?-eq 0] && echo "Start $prog finshed."
Fi
;;
Stop
If [-f $lockfile]; Then
Rm-f $lockfile
[$?-eq 0] && echo "Stop $prog finished."
Else
echo "$prog is not running."
Fi
;;
Restart
If [-f $lockfile]; Then
Rm-f $lockfile
Touch $lockfile
echo "Restart $prog finished."
Else
Touch-f $lockfile
echo "Start $prog finished."
Fi
;;
Status
If [-f $lockfile]; Then
echo "$prog is running"
Else
echo "$prog is stopped."
Fi
;;
*)
echo "Usage: $prog {start|stop|restart|status}"
Exit 1
Esac
Shell Programming Case Statements