一、if判断语句
以一个脚本为例(一般用缩进表示层级关系,相同间距为并列,更多的间距为下属关系)
[root@localhost tmp]# vim num.sh #创建脚本
#!/bin/bash #定义解析的shell
NUM=$1 #定义变量NUM,把第一个参数$1赋值给它
if (($NUM > 4));then #if后面跟判断语句,分号;结束加then,双(())表示运算
echo "This NUM is $NUM bigger" #制表符后跟结果执行语句(符合条件判断时)
else #不符合条件
echo "This NUM is $NUM bigger" #制表符后面跟执行语句
fi #if语句技术标识
[root@localhost tmp]# sh num.sh 2 #执行脚本输出结果
This NUM is 2 bigger
[root@localhost tmp]# sh num.sh 500
This NUM is 500 bigger
判断目录是否存在的脚本
[root@localhost tmp]# vim if_dir.sh
#!/bin/bash
DIR=$1 #定义变量,赋值参数$1
if [ ! -d $DIR ];then #!表示反义 -d判断目录是否存在 -f判断文件是否存在
mkdir -p $DIR #创建目录语句
echo "The $DIR create success." #打印创建目录提示信息
else
echo "The $DIR is exist." #打印已存在提示信息
exit #退出脚本
fi #结束标识符
#下面是执行结果
[root@localhost tmp]# sh -x if_dir.sh /usr/local
+ DIR=/usr/local
+ '[' '!' -d /usr/local ']'
+ echo 'The /usr/local is exist.'
The /usr/local is exist.
+ exit
[root@localhost tmp]# sh -x if_dir.sh /usr/local/b
+ DIR=/usr/local/b
+ '[' '!' -d /usr/local/b ']'
+ mkdir -p /usr/local/b
+ echo 'The /usr/local/b create success.'
The /usr/local/b create success.
#下面执行结果可以看到命令执行结果不影响信息的打印
[root@localhost tmp]# sh -x if_dir.sh -x /usr/local/b
+ DIR=-x
+ '[' '!' -d -x ']'
+ mkdir -p -x
mkdir:无效选项 -- x
请尝试执行"mkdir --help"来获取更多信息。
+ echo 'The -x create success.'
The -x create success.
逻辑运算符解析:
- f 判断文件是否存在 eg: if [ -f filename ]
- d 判断目录是否存在 eg: if [ -d dir ]
- eq 等于 应用于:整型比较 equal
- ne 不等于 应用于:整型比较 not equal
- lt 小于 应用于:整型比较 letter
- gt 大于 应用于:整型比较 greate
- le 小于或等于 应用于:整型比较
- ge大于或等于 应用于:整型比较
- a 双方都成立(and) 逻辑表达式 –a 逻辑表达式
- o 单方成立(or) 逻辑表达式 –o 逻辑表达式
- z 空字符串
多个条件测试判断,从上到下依次判断直到满足条件为止
#!/bin/sh
scores=80
if [[ $scores -gt 85 ]]; then #条件 1
echo "very good!";
elif [[ $scores -gt 75 ]]; then #条件 2
echo "good!";
elif [[ $scores -gt 60 ]]; then #条件 3
echo "pass!";
else #都不满足以上条件的其他情况
echo "no pass!"
fi
二、for循环语句
脚本示例一:(可以用于批量执行的操作)
for var in 对象
do
command #执行语句
done #结束标识符
[root@localhost ~]# vim for_nu.sh
for i in a b c
#!/bin/bash
for i in a b c
do
echo $i
done
#调试执行脚本
[root@localhost ~]# sh -x for_nu.sh
+ for i in a b c
+ echo a
a
+ for i in a b c
+ echo b
b
+ for i in a b c
+ echo c
c
for循环数字累加脚本
[root@localhost tmp]# vim for_nu.sh
#!/bin/bash
j=0
for ((i=1;i<=$1;i++))
do
j=`expr $i + $j` #反单引号表示里面是执行的命令语句
done
echo $j
#调试脚本测试
[root@localhost tmp]# sh for_nu.sh 3
6
[root@localhost tmp]# sh -x for_nu.sh 3
+ j=0
+ (( i=1 ))
+ (( i<=3 ))
++ expr 1 + 0
+ j=1
+ (( i++ ))
+ (( i<=3 ))
++ expr 2 + 1
+ j=3
+ (( i++ ))
+ (( i<=3 ))
++ expr 3 + 3
+ j=6
+ (( i++ ))
+ (( i<=3 ))
+ echo 6
6
网友评论