如何检查相同目录下是否存在具有给定名称的文件?

时间:2018-07-06 15:24:02

标签: bash

给出一个文件名(显示为全名,即当前文件夹中文件的路径),如何检查是否存在(文件名“ filename”的文件夹中),名称为{{ 1}}?

3 个答案:

答案 0 :(得分:1)

如果要给定“ /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

答案 1 :(得分:0)

if [[ -e $(dirname "${startname}")/"f" ]]; then
echo "exists"
fi

检查f${startname}所在的目录是否存在。

答案 2 :(得分:0)

因此,如果我对您的理解正确,那么您想知道邻居文件的路径就可以检查文件“ f”的存在。 这是一个有效的bash shell脚本(我们称它为“ 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/f3 f4
./test/f3 is not present
./test/f4 is not present
相关问题