How to check if a file exists in a shell script

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:

[-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?


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

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

Here is an alternative method using 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 x.txt >> /dev/null 2>&1 && echo yes) || echo no
链接地址: http://www.djcxy.com/p/24130.html

上一篇: 一举测试多个文件条件(BASH)?

下一篇: 如何检查文件是否存在于shell脚本中