#!/bin/bash
if [ $# -lt 1 ];then
echo "Usage:$0 + filepath"
exit
fi #判斷用戶是否輸入了參數(shù)
match=$1 #將要查的文件賦值給變量match
found=0 #定義一個初始變量作為發(fā)生條件,當(dāng)文件找到時對此變量重新賦值
for file in /etc/* #對目錄進行遍歷
do
if [ $file == $match ];then #判斷文件是否匹配
echo "the file $match was found!"
found=1 #當(dāng)文件匹配時,對初始變量重新賦值
break #文件找到后跳出循環(huán)
fi
done
[ $found -ne 1 ] echo "the file $match is not in /etc directory." #做最終的判斷,文件未找到時found仍然是0,判斷條件成立,輸出文件未找到;當(dāng)文件找到時,found被賦值為1,條件不成立,不做輸出。
示例2:對腳本做修改,讓用戶自定義要查找的文件以及在那個目錄下查找
#!/bin/bash
if [ $# -lt 2 ];then
echo "Usage:$0 + filepath + directorypath"
exit
fi
match=$1
found=0
for file in ${2}* #在位置參數(shù)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."