Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check a file exists and execute a command if not?

Tags:

linux

shell

I have a daemon I have written using Python. When it is running, it has a PID file located at /tmp/filename.pid. If the daemon isn't running then PID file doesn't exist.

On Linux, how can I check to ensure that the PID file exists and if not, execute a command to restart it?

The command would be

python daemon.py restart 

which has to be executed from a specific directory.

like image 273
davidmytton Avatar asked Mar 21 '09 18:03

davidmytton


People also ask

Which command is used to check whether file exists or not?

While checking if a file exists, the most commonly used file operators are -e and -f. The '-e' option is used to check whether a file exists regardless of the type, while the '-f' option is used to return true value only if the file is a regular file (not a directory or a device).

Which command correct file if file does not exist?

To test if a file does not exist using the “||” operator, simply check if it exists using the “-f” flag and specify the command to run if it fails. [[ -f <file> ]] || echo "This file does not exist!"

How do you check if a file exists or not empty?

You can use the find command and other options as follows. The -s option to the test builtin check to see if FILE exists and has a size greater than zero. It returns true and false values to indicate that file is empty or has some data.


1 Answers

[ -f /tmp/filename.pid ] || python daemon.py restart 

-f checks if the given path exists and is a regular file (just -e checks if the path exists)

the [] perform the test and returns 0 on success, 1 otherwise

the || is a C-like or, so if the command on the left fails, execute the command on the right.

So the final statement says, if /tmp/filename.pid does NOT exist then start the daemon.

like image 121
eduffy Avatar answered Sep 30 '22 18:09

eduffy