Linux基础(6)
Linux基础(六)
shell脚本中的三大循环和函数知识点
一、流程控制之if结构
1.简单的if实例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/bin/bash var='/etc/init.d' #var='/dev/sda' if [ -d $var ] then echo "$var is directory" elif [ -b $var ] then echo "$var is block" elif [ -f $var ] then echo "$var is regular file" else echo 'unknow' fi
执行效果:
2.向脚本传递参数
eg:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#3.sh echo $0 echo $1 echo $2 echo $3 echo ${11} echo '$$' $$ echo '$*' $* echo '$@' $@ echo '$#' $# echo '$?' $?
测试结果:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
[root@localhost ~]# ./3.sh 1 2 3 4 5 6 7 8 9 10 ./3.sh 1 2 3 $$ 8755 $* 1 2 3 4 5 6 7 8 9 10 $@ 1 2 3 4 5 6 7 8 9 10 $# 10 $? 0
二.循环结构之while
while (条件)
do
动作
done
需要无限循环时我们会选择while :
写个脚本 让用户输入,输入数字通过,输出错误重新输入
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/bin/bash login=0 while [ $login != 1 ] do read -p 'please input your name: ' name read -p 'please input your password: ' pwd if [ $name == 'egon' ] && [ $pwd == '123' ] then echo 'login sucessful' login=1 fi done
运行及查看结果:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
[root@localhost ~]# ./4.sh please input your name: egon please input your password: 123 login sucessful [root@localhost gandong]#
三、循环结构之for
shell格式的for
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for i in {1..10} do echo $i done
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
[root@localhost ~]# ./5.sh 1 2 3 4 5 6 7 8 9 10
应用循环和条件判断写的一个实例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
vim 6.sh while : do read -p 'please input your name: ' name read -p 'please input your password: ' psd if [-z $name ] || [-z $psd ] then continue fi if [ $name = 'alex' -a $psd = 'alex3714' ] then echo 'login successful ,welcome da SB' while : do read -p 'please input your cmd: ' cmd if [ $cmd = 'quit' ] then break fi $cmd done else echo 'username or password is error' fi done echo '========================================================' ~
四、函数知识点
交互shell中的函数
eg:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
vim 7.sh function abc() { echo 'aaa';echo 'bbbb'; } abc
运行结果:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
[root@localhost ~]# vim 7.sh [root@localhost ~]# ./7.sh aaa bbbb