所以,我想做的是查找一组文件,然后让它回显找到的文件。例如,这就是我所拥有的
#!/bin/bash
LaunchDaemon="LaunchDaemon.plist"
launchAgent="LaunchAgent"
mobileLaunchDaemon="MobileDaemon.plist"
mobileAgent="MobileAgent"
if [ -f "$LaunchDaemon" ] || [ -f "$launchAgent" ] || [ -f "$mobileLaunchDaemon" ] || [ -f "$mobileAgent" ]
then
echo "<result>Found</result>"
else
echo "<result>Not Found</result>"
fi
因此,这会告诉我它是否可以找到其中任何一个,但它不会告诉我它正在找到哪一个。我创建了另一个包含elif
语句的语句,它可以工作,但如果它找到第一个,它会停在那里并且不会告诉我其他语句是否也在那里。所以,我希望这是有道理的,我只是想找到一种方法来显示已找到哪些文件。
答案1
您需要将if
测试分成多个
if [ -f "$LaunchDaemon" ]
then
echo $LaunchDaemon found
elif [ -f "$launchAgent" ]
then
echo $launchAgent found
elif [ ...
...
else
echo Not found
fi
类型结构(自己填空。)。
如果您想找到所有匹配项,只需将其作为多个测试进行,设置一个变量以查看是否找到了任何内容
found=0
if [ -f "$LaunchDaemon" ]
then
echo $LaunchDaemon found
found=1
fi
if [ -f "$launchAgent" ]
then
echo $launchAgent found
found=1
fi
...
if [ $found == 0 ]
then
echo Not found
fi
现在有时我们想设置一个变量,以便我们知道找到了哪个变量。这在尝试查找匹配的程序或文件时很常见(例如,在过去我们可能已经有/usr/lib/sendmail
或/usr/sbin/sendmail
取决于操作系统发行版,因此我们需要搜索才能找到它)。
found=
for f in "$LaunchDaemon" "$launchAgent" "$mobileLaunchDaemon" "$mobileAgent"
do
[[ -f "$f" ]] && found="$f"
done
现在我们已经$found
指向一个找到的条目并可以对其进行测试。
if [ -n "$found" ]
then
echo Found: $found
else
echo Nothing found
fi
第二个循环也可以找到全部有微小变化的版本:
found=
for f in "$LaunchDaemon" "$launchAgent" "$mobileLaunchDaemon" "$mobileAgent"
do
[[ -f "$f" ]] && found="$found $f"
done
这样做的缺点是前面可能有一个前导空格,所以我们应该删除它:
found="${found# }"
答案2
数组将是这里最好的方法
#!/bin/bash
#Store the filenames in an array, also less management overhead
arry=( "LaunchDaemon.plist" "LaunchAgent" "MobileDaemon.plist" "MobileAgent" )
#Optioinally if you wish to add one more file to check you could
#uncomment the below line
#arry+=("$1") #One more file added from the command line
for i in "${arry[@]}" #Iterate through each element using a for loop
do
if [ -f "$i" ]
then
echo "<result> $i Found</result>"
else
echo "<result> $i Not Found</result>"
fi
done
答案3
尝试这个
#!/bin/bash
search_LaunchDaemon="LaunchDaemon.plist"
search_launchAgent="LaunchAgent"
search_mobileLaunchDaemon="MobileDaemon.plist"
for filex in ${!search_*}
do
found=${!filex}
#echo -e "${filex}=${!filex}"
#we remove the prefix "search_"
IFS="_" read part1 part2 <<< "${filex}"
if [[ -f $found ]];
then
echo "I have found ${part2}"
else
echo "${part2} not found!"
fi
done