您的位置:首页 > 其它

for循环结合if判断,在目录下查找文件

2018-03-19 18:24 274 查看
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."



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐