Bash Command To Check If File Exists


If you are looking for a bash command to check if file exists then you can try the below options,


Option 1: test command with if-then-else-fi

    Example:
    if test -f my-file.txt; then
        echo "The file exists!"
    else
        echo "The file does not exist!"
    fi

    If you want to look at a specific path,

    if test -f /path-to-file/my-file.txt; then
        echo "The file exists!"
    else
        echo "The file does not exist!"
    fi

Option 2: Using Square Brackets [ ] in one line

    [ -f "data.csv" ] && echo "File exists." || echo "File does not exist."

    Using [ -f "file-name.extention" ] we check if the file exists or not and accordingly echo the result. You can make it more short with -1 to indicate the file does not exists and 1 if it does.

    [ -f "data.csv" ] && echo "1" || echo "-1"
    Bash - Check if file exists or not

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap