How to check if a file exists in bash




















The most readable option when checking whether a file exists or not is to use the test command in combination with the if statement. Always use double quotes to avoid issues when dealing with files containing whitespace in their names. You can also use the test command without the if statement. You can also use the double brackets [[ instead of a single one [. Check if File does Not Exist. Similar to many other languages, the test expression can be negated using the!

The test command includes the following FILE operators that allow you to test for particular types of files:. Check if File does Not Exist Similar to many other languages, the test expression can be negated using the! But we do have some hacks which we can use to check if directory is empty or not- empty. In this example we will list the content of the directory, suppress the output and then based on the exit code check if the directory is empty or contains some content.

We can use find command and then suppress the output to check if the target directory has some content or not. Again as I said since there is no easy way to check if a directory is empty or not using some attributes, we will list the content of the directory. If you get no output then the directory is empty or else not empty. Similarly there are many more attributes which you can use with shell scripts to check for different file types, such as symbolic links, file permissions etc.

Attributes What it does? In this tutorial I shared brief examples of test operators to check for files and directories. You can use any attribute from the table I have shared to enhance your script execution with proper tests. Lastly I hope the steps from the article to check if file exists or not on Linux was helpful. So, let me know your suggestions and feedback using the comment section. If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form. Most of this stuff has been really helpful. But there is no difference in single and double square brackets on the -f example. I always prefer to use double brackets as a general practice as it avoid unexpected surprises at times. You can read more about them at Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

Save my name and email in this browser for the next time I comment. Notify me via e-mail if anyone answers my comment. Table of Contents. Related Posts.



0コメント

  • 1000 / 1000