check if a file or folder exists
Test in a script whether a path exists, is a file, a folder, empty or runnable.
Steps
-
[ -f config.txt ] && echo 'it is a file'a regular file
-
[ -d logs ] || mkdir logsa folder; make it when it is missing
-
[ ! -e path ] && echo 'nothing there'nothing at all by that name
-
[ -s data.csv ] && echo 'not empty'a file that is not empty
-
[ -x script.sh ] && ./script.sha file you may run
-
[ -L link ] && echo 'a symbolic link'a link
Notes
- Quote paths that may have spaces:
[ -f "$file" ]. - In scripts,
if [ -d "$dir" ]; then … fidoes the same over several lines.
Commands used
test
Each has a page in lore: lore test opens it.
Related recipes
- ask for input in a scriptAsk yes or no, read a password without showing it, or wait for an answer with a time limit.
- check if a string contains a textTest in a script whether a string contains, starts with or matches something.
- find the script's own folderInside a script, find the folder the script is in, to reach files next to it.
- get a file's name, folder and extensionTake a path apart in a script: the folder, the name, the name without its extension, the extension.