How To Check If a File Exist In Shell?

Monday, Aug 5, 2024 | 3 minutes read | Update at Monday, Aug 5, 2024

@ İsmail Baydan

In a shell script, you can check if a file exists using the test command or the [ ] notation. For example we need to check if a file exist and want to delete or rename it. Linux bash provides the test command in order to check file existance. Here are some examples of how you can do this:

  1. Using the test command:
if test -f "filename"; then
    echo "File exists."
else
    echo "File does not exist."
fi

Alternatively we can use the [ -f ] operators of the bash to check file existance. But be carefull while using it and do not miss spaces between characters which can lead to error. We provide the file name as argument to the -f . 2. Using the [ ] notation:

if [ -f "filename" ]; then
    echo "File exists."
else
    echo "File does not exist."
fi

In both examples, replace "filename" with the name of the file you want to check.

Additional File Tests

You can also use different options with the test command or [ ] notation to check for other conditions:

  • Check if a directory exists: Sometimes we need to check existance of a directory not a file. The [ -d ] is used to check only directories. We can also provide the path of the directory too.

    if [ -d "directoryname" ]; then
        echo "Directory exists."
    else
        echo "Directory does not exist."
    fi
    
  • Check if a file or directory exists: The [ -e ] is used to chech file or directory existance.

    if [ -e "filename_or_directoryname" ]; then
        echo "File or directory exists."
    else
        echo "File or directory does not exist."
    fi
    
  • Check if a file is readable: The [ -r ] check file existance and also if the file is set readonly.

    if [ -r "filename" ]; then
        echo "File is readable."
    else
        echo "File is not readable."
    fi
    
  • Check if a file is writable: The [ -w ] check file existance and also if the file is set writable.

    if [ -w "filename" ]; then
        echo "File is writable."
    else
        echo "File is not writable."
    fi
    
  • Check if a file is executable: The [ -x ] check file existance and also if the file is executable.

    if [ -x "filename" ]; then
        echo "File is executable."
    else
        echo "File is not executable."
    fi
    

These checks can be useful for ensuring that files or directories meet certain conditions before proceeding with operations in your shell scripts.

“[-e: command not found” Error

If you get the [-e: command not found error this means there is a typing error like not using space between square brackets and -e. The following bash script will return error.

[-e myfile.txt]

Correct usage is like below.

[ -e myfile.txt ]

© 2024 Linux and Python Tutorials

🌱 Powered by Hugo with theme Dream.