Bash 如何检查同一目录中是否存在具有给定名称的文件?
给定一个文件名(显示为全名,即当前文件夹中的文件路径),我如何检查是否存在(在文件“filename”的文件夹中),文件名为Bash 如何检查同一目录中是否存在具有给定名称的文件?,bash,Bash,给定一个文件名(显示为全名,即当前文件夹中的文件路径),我如何检查是否存在(在文件“filename”的文件夹中),文件名为f?如果您想要的是给定的“/long/path/name.txt”,确定当前目录中是否存在名为“name.txt”的文件,然后: LONG=/long/path/name.txt SHORT=${LONG##*/} if [ -f "$SHORT" ]; then echo file exists else echo file does not exist
f
?如果您想要的是给定的“/long/path/name.txt”,确定当前目录中是否存在名为“name.txt”的文件,然后:
LONG=/long/path/name.txt
SHORT=${LONG##*/}
if [ -f "$SHORT" ]; then
echo file exists
else
echo file does not exist
fi
要检查
f
是否与${startname}
存在于同一目录中。因此,如果我理解正确,您需要检查文件“f”是否存在,并知道相邻文件的路径。下面是一个bashshell脚本(我们称之为“findNeighborFile.sh”),它实现了以下功能:
#!/bin/bash
neighbor=$1
target=$2
directory=$(dirname "${neighbor}")
if [ -f "$neighbor" ]; then
echo "$neighbor is present"
if [ -f "$directory/$target" ]; then
echo "$directory/$target is present"
else
echo "$directory/$target is not present"
fi
else
echo "$neighbor is not present"
if [ -f "$directory/$target" ]; then
echo "$directory/$target is present"
else
echo "$directory/$target is not present"
fi
fi
该脚本包含两个参数:第一个是相邻文件路径,第二个是要查找的目标文件。假设您有一个名为“test”的目录,它与脚本位于同一目录中,“test”包含两个文件“f1”、“f2”。现在,您可以尝试不同的测试用例: 两个文件都存在:
./findNeighborFile.sh ./test/f1 f2
./test/f1 is present
./test/f2 is present
目标不存在:
./findNeighborFile.sh ./test/f1 f3
./test/f1 is present
./test/f3 is not present
./test/f3 is not present
./test/f2 is present
邻居不存在:
./findNeighborFile.sh ./test/f1 f3
./test/f1 is present
./test/f3 is not present
./test/f3 is not present
./test/f2 is present
两个文件都不存在:
./findNeighborFile.sh ./test/f3 f4
./test/f3 is not present
./test/f4 is not present
澄清:给定“/home/whatever/name.txt”,您想知道当前目录中是否存在“name.txt”?您必须更具体,您使用的是什么语言?在哪种环境下?@AlyShmahell它被标记为bash,所以我猜是bash。@AlyShmahell他在问题中标记了bash。哦,对不起,我当时没有注意到。