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;
}
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!"
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With