Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute certain commands if a file does NOT exist?

Tags:

file

shell

I would like to check if a file exists, then if it does not, create it.

Consider an equivalent of the following C code but with shell scripting.

if(!exist) {
    command;
    command;
}
else {
    command;
    command;
}
like image 325
Dragos Rizescu Avatar asked Nov 24 '13 19:11

Dragos Rizescu


People also ask

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

Checking if a file exists is a very common task. To search for relevant questions, use the search bar (top right). I got lots of results with the terms "bash script file exists"

In any case, you want either the test builtin or its semantic equivalent [ ]:

[ ! -e your_file ] && >your_file

or

test ! -e your_file && >your_file

which will first test that your_file does not (!) exist (-e) and creates it if that's the case.

For more information on the different tests you can run (other than -e), you can type:

help -m test | less
like image 144
Joseph R. Avatar answered Oct 18 '22 11:10

Joseph R.