Linux脚本结构化命令

版权声明:转载请注明出处 https://blog.csdn.net/u010502101/article/details/81843384

一、if结构

1、shell命令退出状态作if的判断条件
格式

if command
then
    commands
else
    commands
fi

其中command为shell命令,shell命令执行完毕后,退出状态为0表示执行成功,执行if中命令;非0为不成功,执行else中命令。

新建script7脚本,执行脚本时根据传入的参数判断是否在file文件中

echo $1
pattern=$1
if grep $pattern file
then
    echo "在file文件中存在$pattern"
else
    echo "在file文件中不存在$pattern"
fi

其中file文件中内容:

The dog:There is a big dog and a little dog in the park
The cat:There is a big cat and a little cat in the park
The tiger:There is a big tiger and a litle tiger in the park

执行脚本,传入dog参数

root@lzj-virtual-machine:/home/lzj/demo# ./script8 dog
dog
The dog:There is a big dog and a little dog in the park
在file文件中存在dog

2、test命令的退出状态作为if的判断条件
if除了根据shell命令进行判断,还可以借助test命令对其它条件进行判断
格式

if test condition
then
    commands
else
    commands
fi

或者

#"["前面后面和"]"前都要加空格
if [ condition ]
then
    commands
else
    commands
fi

如果condition条件为true,则test命令的退出条件为0,执行if中命令;否则非0,执行else中命令。

例如,新建script9脚本,其内容为

num=10
if [ $num -gt 5 ]
then
    echo "num大于5"
else
    echo "num小于5"
fi

执行该脚本

root@lzj-virtual-machine:/home/lzj/demo# ./script9 
num大于5

TIP:
在test中,数值比较参数
这里写图片描述

在test中,字符串比较参数
这里写图片描述

在test中,文件比较
这里写图片描述

3、判断条件为数学表达式的,可以用双圆括号表示

num=5
if (( $num ^ 2 > 100 ))
then
    echo $[ $num * 2 ]
fi

除了2中列举的数学操作外,在双圆括号中还可以用下面的数学操作符
这里写图片描述

4、判断条件为字符串的,可以用双方括号表示
除了2中列举的字符串比较符号,双方括号中还可以进行模式匹配

name=lzj
if [[ $name == l* ]]
then
    echo $name
fi

运行会输出“lzj”

另外上面四种方式,都可以用多重循环

if [ condition1 ] && [ condition2 ]
then
    commands
elif [ condition1 ] || [ condition2 ]
then
    commands
elif [ condition ]
then
    commands
else
    commands
fi

二、case结构

case var in
pattern1) 
    command1
    command2;;
pattern2 | pattern3)
    command1
    command2;;
pattern3)
    command;;
*)
    commands;;

三、for循环

格式:

for var in list
do
    commands
done

1、读取列表值

list="Bob Tom Terry Lily"
for name in $list
do
    echo "hello $name"
done

运行脚本,输出

hello Bob
hello Tom
hello Terry
hello Lily

for循环还可以遍历目录

for file in /home/lzj/demo/*
do
    echo $file
done

运行脚本,输出

/home/lzj/demo/4
/home/lzj/demo/file
/home/lzj/demo/file1
/home/lzj/demo/file2
/home/lzj/demo/file3
/home/lzj/demo/file4
/home/lzj/demo/file5

2、改变for循环分隔符
shell中IFS默认为空白字符,包括空格、制表符、换行符。 for循环中默认是按空白字符就行分割的,下面修改默认分隔符。

file_name="file"
IFS=$'\n'
for line in `cat $file_name`
do
    echo $line
done

运行脚本,输出

The dog:There is a big dog and a little dog in the park
The cat:There is a big cat and a little cat in the park
The tiger:There is a big tiger and a litle tiger in the park

可知,按行进行分割的。

四、while循环

格式

while test command
do
    commands
done

或者

while [ command ]
do
    commands
done

例如

var=1
sum=0
while [ $var -lt 10 ]
do
    sum=$[$sum + $var] 
    var=$[$var + 1]
done
echo $sum

TIPS:在for循环、while循环中依然支持break、continue用法。
对于for循环、while循环,还可以把循环中输出重定向到文件中

for file in /home/lzj/demo/*
do
    echo $file
done > /home/log/log.txt

猜你喜欢

转载自blog.csdn.net/u010502101/article/details/81843384
今日推荐