Test if a File Exists in Ubuntu and Delete

Use the test command to test if a file exists and delete the file if it exists. Or output a message that the file does not exist:

sudo test -e /tmp/filename && sudo rm /tmp/filename && echo “file exists and was removed” || echo “file does not exist”;

More examples:

test -e file = file exists
test -x file = …is executable
test -w file = …is writable
test -r file = …is readable
test -s file = …is not empty
test -d file = …is a directory
test -f file = …is a regular file (not a device driver or directory)
test string1 = string2 = test whether string1 is the same as string2
test string1 != string2 = test whether string1 is not the same as string2
[ expression ] can also be used instead of test expression

man test for more information.

Leave a Reply