How to check if a file exists in a shell script

Kurt Peek picture Kurt Peek · Oct 17, 2016 · Viewed 387.7k times · Source

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

chris01 picture chris01 · Oct 17, 2016

You're missing a required space between the bracket and -e:

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