Shell Advanced Tutorial-Lesson 1 Application of Case Statement

Shell Advanced Tutorial-Lesson 1 Application of Case Statement

1. Introduction to case statement
For example, start httpd service
start
stop
reload
restart

acl访问控制 匹配即停止。

case语句主要适用于,某个变量存在多种取值,需要对其中的每一种取值分别执行不同的命令序列。
case语句匹配一个值与一个模式,如果匹配成功则执行所匹配的命令序列。

2. The structure of the case statement

case $i in
	mode1)
		commands1
		;;
	mode2)
		commands2
		;;
	*)
		default commands
		;;
esac

Note: { 1. The value must be followed by the keyword in; 2. Each mode must end with a closing bracket ")"; 3. The value can be a specific value or a variable; 4. The esac keyword is very important, Represents the end of the case statement; 5. Regarding the double semicolon, represents the technique of command sequence; }





3. Case statement execution flow { Pattern matching: After the match finds that the value matches a certain pattern, all commands in the meantime begin to execute until ;;. The value will detect every pattern that matches. Once the pattern matches, no other patterns will continue after executing the corresponding command of the matched pattern. If there is no matching pattern, use an asterisk * to capture the value, and then execute the following commands. }




4. Small example
Script name: untar.sh
Function: Unzip files in batches.
Script realization ideas: { 1. The file is a compressed package (tar.gz, tar.bz2) 2. The command to unzip the file (tar.gz(tar zxf file) ,tar.bz2(tar jxf file) 3. Make the file in the test environment { tar zcf /home/passwd.tar.gz /etc/passwd tar zcf /home/passwd.tar.bz2 /etc/passwd } } Script content { #!/bin/bash









FILE=/home/

case $1 in 
	*.tar.gz)
		tar zxf $FILE$1
		if [ $? -eq 0 ]
			then
				echo "$1 success!"
			else
				echo "$1 false!"
		fi
	;;
	*.tar.bz2)
		tar jxf $FILE$1
		if [ $? -eq 0 ]
			then
				echo "$1 success!"
			else
				echo "$1 false!"
		fi
	;;
	*)
		echo "Please Use {tar.gz|tar.bz2} format file !"
	;;
esac
}

执行结果

[root @
centos home] # ls passwd.tar.bz2 passwd.tar.gz untar.sh
[root @ centos home] # sh untar.sh passwd.tar.gz
passwd.tar.gz success!
[root @
centos home] # ls etc passwd.tar.bz2 passwd.tar.gz untar.sh
[root @ centos home] # ls etc /
passwd

Guess you like

Origin blog.csdn.net/weixin_45603370/article/details/110919106