Check if File Does Not Exist in Bash

Fumbani Banda Mar 24, 2022 Oct 24, 2021
Check if File Does Not Exist in Bash

This tutorial checks if a regular file does not exist in bash with the test command.

Check if a file does not exist with test in Bash

The test command has a logical not operator, which is ! . We will also add the -f option to specify a file. In this case, the condition tests if the file does not exist.

#!/bin/bash
if [ ! -f check_fil.sh ];
then
     printf 'No such file\n'
else
     printf 'File exists\n'
fi

Output:

No such file
Fumbani Banda avatar Fumbani Banda avatar

Fumbani is a tech enthusiast. He enjoys writing on Linux and Python as well as contributing to open-source projects.

LinkedIn GitHub

Related Article - Bash File