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."
示例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."
相关文章推荐
- 14 While、For循环及if条件判断
- python if条件判断、for循环和while循环
- 20.5 shell脚本中的逻辑判断 20.6 文件目录属性判断20.7 if 特殊用法 20.8/20.9 case判断
- 实现1+2+3...+n,要求不能使用乘除法、循环、条件判断、选择相关的关键字(for、while、if、else、switch、case)。
- for判断是目录还是文件
- Java实现1+2+...+n,不用乘除符号,不用if等条件判断,不用for等循环
- Linux命令 find和mv的结合使用:查找文件,移动到某个目录
- 20.5 shell脚本中的逻辑判断 20.6 文件目录属性判断 20.7 if特殊用法 20.8/20.9 case判断
- python 列表处理,for循环语句,if条件判断
- 求1+2+…+n,要求不能使用乘除法、for、while、if、else、s witch、case 等关键字以及条件判断语句(A?B:C)和不用循环/goto/递归输出1~100的10种写法
- Python3学习笔记【基础3--list,tuple,if条件判断,for/while循环,dict字典,set集合】
- c++中的结构化语句 判断语句if 分支语句switch 循环语句 while 和 do while 循环语句for的使用
- 条件判断之if、case语句和文件查找命令
- Python入门(三):if判断、for和while循环、break和continue
- Python基础(条件判断和循环) if elif else for while break continue;
- if/switch/while/do while/for/等循环及判断的简要用法案例
- Python基础--循环for、while,判断if
- shell脚本 for循环实现文件和目录遍历
- Linux学习--第十一天--source、环境变量目录、欢迎信息、正则、cut、awk、sed、sort、判断表达式、if、for、case、一些脚本
- for,while循环,if判断格式