Linux Shell在目录下使用for循环结合if查找文件的巧用
1.for循环对目录做遍历,if判断文件是否为要查找的文件。
示例1:
#!/bin/bash if [ $# -lt 1 ];then echo "Usage:$0 + filepath" exit fi #判断用户是否输入了参数 match=$1 #将要查的文件赋值给变量match found=0 #定义一个初始变量作为发生条件,当文件找到时对此变量重新赋值 for file in /etc/* #对目录进行遍历 do if [ $file == $match ];then #判断文件是否匹配 echo "the file $match was found!" found=1 #当文件匹配时,对初始变量重新赋值 break #文件找到后跳出循环 fi done [ $found -ne 1 ] && echo "the file $match is not in /etc directory." #做最终的判断,文件未找到时found仍然是0,判断条件成立,输出文件未找到;当文件找到时,found被赋值为1,条件不成立,不做输出。
示例2:对脚本做修改,让用户自定义要查找的文件以及在那个目录下查找
#!/bin/bash if [ $# -lt 2 ];then echo "Usage:$0 + filepath + directorypath" exit fi match=$1 found=0 for file in ${2}* #在位置参数2,用户给定的目录中(一层目录)遍历所有文件 do if [ $file == $match ];then echo "the file $match was found!" found=1 break fi done [ $found -ne 1 ] && echo "the file $match is not in /etc directory."
相关推荐
laisean 2020-11-11
xiaonamylove 2020-08-16
tianhuak 2020-11-24
以梦为马不负韶华 2020-10-20
彼岸随笔 2020-10-20
yutou0 2020-10-17
applecarelte 2020-10-16
ourtimes 2020-10-16
huha 2020-10-16
大牛牛 2020-10-30
firefaith 2020-10-30
liguojia 2020-10-20
wangzhaotongalex 2020-10-20
JohnYork 2020-10-16
Julyth 2020-10-16
laisean 2020-09-27
flycappuccino 2020-09-27
liguojia 2020-09-27
wangzhaotongalex 2020-09-22
流年浅滩 2020-10-23
liujianhua 2020-10-22
woaimeinuo 2020-10-21
tufeiax 2020-09-03
laisean 2020-09-01
vvu 2020-09-16
libao 2020-09-16
Yyqingmofeige 2020-08-18