如何检查shell脚本中是否存在文件

时间:2022-05-19 18:13:00

I'd like to write a shell script which checks if a certain file, archived_sensor_data.json, exists, and if so, deletes it. Following http://www.cyberciti.biz/tips/find-out-if-file-exists-with-conditional-expressions.html, I've tried the following:

我想编写一个shell脚本来检查某个文件archived_sensor_data.json是否存在,如果存在,则删除它。在http://www.cyberciti.biz/tips/find-out-if-file-exists-with-conditional-expressions.html之后,我尝试了以下方法:

[-e archived_sensor_data.json] && rm archived_sensor_data.json

However, this throws an error

但是,这会引发错误

[-e: command not found

when I try to run the resulting test_controller script using the ./test_controller command. What is wrong with the code?

当我尝试使用./test_controller命令运行生成的test_controller脚本时。代码有什么问题?

3 个解决方案

#1


180  

Blank missing between bracket and -e.

括号和-e之间缺少空白。

#!/bin/bash
if [ -e x.txt ]
then
    echo "ok"
else
    echo "nok"
fi

#2


12  

Here is an alternative method using ls:

这是使用ls的替代方法:

(ls x.txt && echo yes) || echo no

If you want to hide any output from ls so you only see yes or no, redirect stdout and stderr to /dev/null:

如果你想隐藏ls的任何输出所以你只看到是或否,将stdout和stderr重定向到/ dev / null:

(ls x.txt >> /dev/null 2>&1 && echo yes) || echo no

#3


1  

Internally, the rm command must test for file existence anyway,
so why add another test? Just issue

在内部,rm命令必须测试文件是否存在,那么为什么要添加另一个测试呢?刚发行

rm filename

and it will be gone after that, whether it was there or not.
Use rm -f is you don't want any messages about non-existent files.

它会在那之后消失,无论它是否存在。使用rm -f是不希望有关于不存在的文件的任何消息。

If you need to take some action if the file does NOT exist, then you must test for that yourself. Based on your example code, this is not the case in this instance.

如果文件不存在需要采取某些操作,那么您必须自己测试。根据您的示例代码,在这种情况下不是这种情况。

#1


180  

Blank missing between bracket and -e.

括号和-e之间缺少空白。

#!/bin/bash
if [ -e x.txt ]
then
    echo "ok"
else
    echo "nok"
fi

#2


12  

Here is an alternative method using ls:

这是使用ls的替代方法:

(ls x.txt && echo yes) || echo no

If you want to hide any output from ls so you only see yes or no, redirect stdout and stderr to /dev/null:

如果你想隐藏ls的任何输出所以你只看到是或否,将stdout和stderr重定向到/ dev / null:

(ls x.txt >> /dev/null 2>&1 && echo yes) || echo no

#3


1  

Internally, the rm command must test for file existence anyway,
so why add another test? Just issue

在内部,rm命令必须测试文件是否存在,那么为什么要添加另一个测试呢?刚发行

rm filename

and it will be gone after that, whether it was there or not.
Use rm -f is you don't want any messages about non-existent files.

它会在那之后消失,无论它是否存在。使用rm -f是不希望有关于不存在的文件的任何消息。

If you need to take some action if the file does NOT exist, then you must test for that yourself. Based on your example code, this is not the case in this instance.

如果文件不存在需要采取某些操作,那么您必须自己测试。根据您的示例代码,在这种情况下不是这种情况。