Kurt Peek Kurt Peek - 1 month ago 8
Bash Question

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?

Answer

Blank missing between bracket and -e.

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