• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Test if a file exists with the BASH shell

Test if a file exists with the BASH shell

Often when shell scripting with BASH you need to test if a file exists (or doesn’t exist) and take appropriate action. This post looks at how to check if a file exists with the BASH shell.

To test if the /tmp/foo.txt file exists, you would do the following, changing the echo line to whatever action it is you want to take:

if [ -f /tmp/foo.txt ]
then
    echo the file exists
fi

Note that there must be whitespace between the "if" and "[", the "[" and "-f" and the filename and the closing "]" otherwise you will get error messages along the lines of:

[-f: command not found
[: missing `]'
No such file or directory
syntax error near unexpected token `then'

If you want to do something if the file exists and something else if the file doesn’t then you can use an "else" clause like so, again changing the echo line to some other suitable action:

if [ -f /tmp/foo.txt ]
then
    echo the file exists
else
    echo the file does not exist
fi

And finally, if you want to check if a file does not exist, then you can do this:

if [ ! -f /tmp/foo.txt ]
then
    echo the file does not exist
fi

Again, you need to make sure there is white space on either side of the !, otherwise you’ll get error messages like this:

[!-f: command not found
[!: command not found
[: !-f: unary operator expected

And finally, if you want to do the same sorts of tests to see if a directory exists using the BASH shell, the use the -d flag instead, e.g.:

if [ -d /tmp ]
then
    echo the directory exists
fi

Check Out These Related posts:

  1. Create a file in Linux
  2. How To Use Bash if else Statement
  3. Type casting with PHP
  4. Bash Check if File Exists

Filed Under: Linux/Unix/BSD

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap