gpt4 book ai didi

linux - 脚本检查文件是否存在

转载 作者:太空宇宙 更新时间:2023-11-04 04:44:04 25 4
gpt4 key购买 nike

我正在尝试制作脚本来检查文件是否存在。文件名通过参数传递。该脚本正在检查当前目录中是否存在文件。

#!/bin/bash

tmp=$(find $1)
failure="find: ‘$1‘: No such file or directory"

if [ "$tmp" != "$failure" ]; then
echo "file exists"
else
echo "file not exists"
fi

我正在创建两个变量。第一个结果为 find命令,第二个保存失败消息 find命令。在 if声明我正在比较这些变量。

即使文件存在,我总是得到 else声明消息。这段代码有什么问题?

最佳答案

如果您的文件位于当前路径本身,则无需使用find,以下内容可能会对您有所帮助。

#!/bin/bash
filename=$1
if [[ -f "$filename" ]]; then
echo "file exists"
else
echo "file does not exists"
fi

然后将脚本运行为 script.ksh file_name 另外,如果您需要验证文件是否存在并且具有一定大小,则将上面代码中的 -f 更改为 -s

您还可以在您的盒子中进行man test来检查所有这些类型的条件。

关于linux - 脚本检查文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49590881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com