Shell脚本编程---使用结构化命令(二)

一、使用if—then语句

if--then语句的格式如下:

if command
then
    commands
fi

例子:

[root@ceph01 test]# cat if-then.sh 
#!/bin/bash
# testing multiple commands in the then section
testuser=root
if grep $testuser /etc/passwd
then
	echo The bash files for user $testuser are:
	ls -a /$testuser/.b*
fi

运行脚本

[root@ceph01 test]# ./if-then.sh 
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
The bash files for user root are:
/root/.bash_history  /root/.bash_profile
/root/.bash_logout   /root/.bashrc

二、if—then—else语句

if-then-else语句的命令格式:

if command
then
    command
else
    command
fi

例子:

[root@ceph01 test]# cat if-then-else.sh 
#!/bin/bash
# testing the else section
testuser=badtest
if grep $testuser /etc/passwd
then
	echo The files for user $testuser are:
	ls -a /$testuser/.b*
else
	echo "The user name $testuser doesn't exist on this system"
fi

运行脚本:

[root@ceph01 test]# ./if-then-else.sh 
The user name badtest doesn't exist on this system

三、嵌套if语句

有时需要在脚本代码中检查几种情况,这时可以不必编写单独的if-then语句,可以使用else部分的另一版本,称为elif

elif以另一个if-then语句继续else部分:

if    command1
then 
     commends
elif   command2
then 
     more   commands
fi

 

也可以把多个elif语句串在一起,创建一个大的if-then-elif组:

if command1
then 
    command set 1
elif command2
then
    command set 2
elif command3
then 
    command set 3
elif command4
then
    command set 4
fi

 

四、test命令

       test命令提供一种检测if-then语句中不同条件的的方法。如果test命令中列出的条件评估值为true,test命令以0退出状态代码退出,这使if-then语句使用与其他编程语言中的if-then语句一样的方式运行。如果条件为false,则test命令退出,使得if-then语句失败。

test命令的格式:

test condition
if  test  condition
then 
       commands
fi

test命令提供一种检测if-then语句,test评估以下三类:数值比较;字符串比较;文件比较。

1>数值比较:

[root@ceph01 test]# cat test-value.sh 
#!/bin/bash
#using numeric test comparisons
val1=10
val2=11
if [ $val1 -gt 5 ]           #测试val1是否大于5
then
	echo "The test value $val1 is greater than 5"
fi

if [ $val1 -eq $val2 ]       #测试val1和val2是否相等
then 
	echo "The values are equal"
else
	echo "The values are different"
fi 

 

 

 

运行脚本:

[root@ceph01 test]# ./test-value.sh 
The test value 10 is greater than 5
The values are different

2>字符串比较:

字符串相等

[root@ceph01 test]# cat test-string.sh 
#!/bin/bash
#testing string equality
testuser=root

if [ $USER != $testuser ]
then
	echo "This isn't $testuser"
else
	echo "Welcome $testuser"
fi

运行脚本:

[root@ceph01 test]# ./test-string.sh 
Welcome root

字符串顺序:

大于和小宇符号一定要转义,否则shell会当做重定向符号;

大于和小于顺序与在sort命令中的顺序不同

[root@ceph01 test]# cat test-string-order.sh 
#!/bin/bash
#mis-using string comparisons

val1=bashball
val2=hockey

if [ $val1 > $val2 ]
then
	echo "$val1 is greater than $val2"
else
	echo "$val1 is less than $val2"
fi

运行脚本:

[root@ceph01 test]# ./test-string-order.sh 
bashball is greater than hockey

字符串大小

[root@ceph01 test]# cat test-string-length.sh 
#!/bin/bash
#testing string length

val1=testing
val2=''

if [ -n $val1 ]
then
	echo "Test string '$val1' is not empty"
else
	echo "The string '$val1' is empty"
fi

if [ -z $val2 ]
then
	echo "The string '$val2' is empty"
else
	echo "The string '$val2' is not empty"
fi

if [ -z $val3 ]
then
	echo "The string '$val3' is empty"
else
	echo "The string '$val3' is not empty"
fi

运行脚本:

[root@ceph01 test]# ./test-string-length.sh 
Test string 'testing' is not empty
The string '' is empty
The string '' is empty

3>文件比较

检查目录

[root@ceph01 test]# cat test-file-leap.sh 
#!/bin/bash
# look before you leap

if [ -d $HOME ]
then
	echo "Your HOME directory exists"
	cd $HOME
	ls -a
else
	echo "There's a problem with your HOME directory"
fi

运行脚本:

[root@ceph01 test]# ./test-file-leap.sh 
Your HOME directory exists
.				 .cshrc
..				 fio-ceph.sh
anaconda-ks.cfg			 force-eth0-100Mbps.sh
.ansible			 lvm-resize-sda.sh
.bash_history			 .pki
.bash_logout			 .ssh
.bash_profile			 .tcshrc
.bashrc				 updates
.cache				 .viminfo
CentOS-7-aarch64-Everything.iso  .Xauthority
.config

检查对象是否存在

[root@ceph01 test]# cat test-file-checking.sh 
#!/bin/bash
# checking if a directory exists

if [ -e $HOME ]
then
	echo "OK on the directory,now let's check the file"
	#checking if a file exists
	if [ -e $HOME/testing ]
	then
		#the file exists,append data to it
		echo "Appending date to existing file"
		date >> $HOME/testing
	else
		#the file doesn't exist,create a new file
		echo "Creating new file"
		date > $HOME/testing
	fi
else
	echo "Sorry,you don't have a HOME directory"
fi

运行脚本:

[root@ceph01 test]# ./test-file-checking.sh 
OK on the directory,now let's check the file
Creating new file

[root@ceph01 test]# ./test-file-checking.sh 
OK on the directory,now let's check the file
Appending date to existing file

检查文件

[root@ceph01 test]# cat test-file-check.sh 
#!/bin/bash
# check if a file

if [ -e $HOME ]
then
	echo "The object exists,is it a file"
	if [ -f $HOME ]
	then
		echo "Yes,it's a file!"
	else
		echo "No,it's not a file!"
		if [ -f $HOME/.bash_history ]
		then
			echo "But this is a file!"
		fi
	fi
else
	echo "Sorry,the object doesn't exist"
fi

运行脚本:

[root@ceph01 test]# ./test-file-check.sh 
The object exists,is it a file
No,it's not a file!
But this is a file!

是否能读

[root@ceph01 test]# cat test-file-read.sh 
#!/bin/bash
#testing if you can read a file 
pwfile=/etc/shadow

#first,test if the file exists,and is a file
if [ -f $pwfile ]
then
	#new test if you can read it
	if [ -r $pwfile ]
	then
		tail $pwfile
	else
		echo "Sorry,I'm unable to read the $pwfile file"
	fi
else
	echo "Sorry,the file $file doesn't exist"
fi

 

运行脚本:

[root@ceph01 test]# ./test-file-read.sh 
gnome-initial-setup:!!:17530::::::
rpcuser:!!:17530::::::
nfsnobody:!!:17530::::::
avahi:!!:17530::::::
postfix:!!:17530::::::
sshd:!!:17530::::::
ntp:!!:17530::::::
oprofile:!!:17530::::::
tcpdump:!!:17530::::::
ceph:!!:17885::::::

检查空文件

[root@ceph01 test]# cat test-file-null.sh 
#!/bin/bash
#testing if a file is empty
file=t15test
touch $file

if [ -s $file ]
then
	echo "The $file file exists and has data in it"
else
	echo "The $file exists and is empty"
fi

date > $file
if [ -s $file ]
then
	echo "The $file file has data in it "
else
	echo "The $file is still empty"
fi

运行脚本

[root@ceph01 test]# ./test-file-null.sh 
The t15test exists and is empty
The t15test file has data in it 

检查是否能够向文件中写入数据

-w比较确定是否有权能够向文件中写入数据

[root@ceph01 test]# cat test-file-check-write.sh 
#!/bin/bash
# checking if a file is writeable

logfile=$HOME/t16test
touch $logfile
chmod u-w $logfile
now='date +%Y%m%d-%H%M'

if [ -w $logfile ]
then
	echo "The program ran at: $now" > $logfile
	echo "The first attempt succeeded"
else
	echo "The first attempt failed!"
fi

chmod u+w $logfile
if [ -w $logfile ]
then
	echo "The program ran at: $now" > $logfile
	echo "The second attempt succeeded"
else
	echo "The second attempt failed"
fi

运行脚本:

[root@ceph01 test]# ./test-file-check-write.sh 
The first attempt succeeded
The second attempt succeeded

检查是否能够运行文件

-x比较你是否有指定文件的运行权限

[root@ceph01 test]# cat test-file-check-run.sh 
#!/bin/bash
# testing file execution

if [ -x test-file-checking.sh ]
then
	echo "You can run the script:"
	./test-file-checking.sh
else
	echo "Sorry,you are unable to execute the script"
fi

运行脚本:

[root@ceph01 test]# ./test-file-check-run.sh 
You can run the script:
OK on the directory,now let's check the file
Appending date to existing file

检查所有权

-o比较可以容易地检查你是否是文件的所有者:

[root@ceph01 test]# cat test-file-check-ownser.sh 
#!/bin/bash
# check file ownsership
if [ -o /etc/passwd ]
then
	echo "You're the owner of the /etc/passwd file"
else
	echo "Sorry,you're not the owner of the /etc/passwd file"
fi

运行脚本:

[root@ceph01 test]# ./test-file-check-ownser.sh 
Sorry,you're not the owner of the /etc/passwd file

检查文件日期

      -nt比较确定一个文件是否比另一个文件新,如果一个文件更新,他就是一个更近的文件创建时间。-ot比较确定一个文件是否比另一个文件更旧,如果文件更旧,它会有一个比较久远的创建时间:

[root@ceph01 test]# cat test-file-check-date.sh 
#!/bin/bash
# testing file dates

if [ ./outfile -nt ./test-file-check.sh ]
then
	echo "The outfile file is newer than test-file-check.sh"
else
	echo "The test-file-check.sh file is newer than outfile"
fi

if [ ./outfile -ot ./test-fiel-check.sh ]
then
	echo "The outfile file is older than the test-file-check.sh"
fi

运行脚本:

[root@ceph01 test]# ./test-file-check-date.sh 
The test-file-check.sh file is newer than outfile

五、复合条件检查(布尔操作符:&&    ||)

if-then语句可以使用布尔逻辑来合并检查条件,可以使用两个布尔操作符:

[ condition ] && [ condition2 ]
[ condition ] || [ condition2 ]

&&:AND布尔操作符(两者都成立才会执行then)

||   :OR布尔操作符(两者满足其一就会执行then)

[root@ceph01 test]# cat bool.sh 
#!/bin/bash
# testing compound comparisons

if [ -d $HOME ] && [ -w $HOME/testing ]
then
	echo "The file exists and you can write to it"
else
	echo "I can't write to the file"
fi

运行脚本:

[root@ceph01 test]# ./bool.sh 
The file exists and you can write to it

六、if-then的高级特征

      双圆括号表示数学表达式;

      双方括号表示高级字符串处理函数。

(1)双圆括号

双圆括号命令允许在比较中包含高级数学公式。双圆括号命令的格式是:

((expression))

[root@ceph01 test]# cat double-parenthesis.sh 
#!/bin/bash
# using double parenthesis

val1=10

if (( $val1 ** 2 > 90 ))
then
	(( val2 = $val1 ** 2 ))
	echo "The square of $val1 is $val2"
fi

运行脚本:

[root@ceph01 test]# ./double-parenthesis.sh 
The square of 10 is 100

(2)双方括号

双方括号命令为字符串比较提供高级功能,格式为:[ [ expression ] ]

[root@ceph01 test]# cat pattern-matching.sh 
#!/bin/bash
# using pattern matching
if [[ $USER == r* ]]
then
	echo "Hello $USER"
else
	echo "Sorry,I don't know you"
fi

运行脚本:

[root@ceph01 test]# ./pattern-matching.sh 
Hello root

七、case命令

case命令将指定的变量与不同的模式进行比较。如果变量与模式匹配,shell执行为该模式指定的命令。

命令格式:

case   Varisble  in

pattern1  |  pattern2)  commands1;

pattern3)   commands2;;

*)  default  commands;;

esac

示例:

[root@ceph01 test]# cat case.sh 
#!/bin/bash
# using the case command

case $USER in
root | barbara)
	echo "Welcome $USER"
	echo "Please enjoy your visit";;
testing)
	echo "Special testing account";;
jessica)
	echo "Don't forget to log off when you're done";;
*)
	echo "Sorry,you're not allowed here";;
esac

运行脚本:

[root@ceph01 test]# ./case.sh 
Welcome root
Please enjoy your visit

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值