BASH check to see if a file exists – Linux bash is a very powerful tool. It has so many different things you can do with it. Bash has a whole tool box of methods that can be used in regards file and directory related functions. You are able to create, delete, change and check whether it is there.
What we are going to go through today is the answer to the question ‘How to check if a file exists’. We will look how to check a file or directory to see if it exists with the BASH shell.The best way is to create a bash script to do this check.
That way you only need to write it once and add the file name you are looking for. We will first test to see if the /foo/myfile.txt file exists. You could use the below script, just change the echo line to whatever action you want to see, or you want it to take, which could be delete it.
if [ -f /foo/myfile.txt ] ; then echo "the file exists"; fi
This will tell you once it has found the file, but what if you wanted to make sure the file doesn’t exist.
Well then we would run the below script, which reveres the Boolean result using the !
if [ ! -f /foo/myfile.txt ] ; then echo "the file does not exist"; fi
The above uses the square bracket syntax but you can also use the format that uses the ‘ test ‘
test -f /foo/myfile.txt
Then you would use the $? To get the answer of the command.
Although this would return a boolean true or false – 1 or 0 . The below is an example if the file existed;
test -f /foo/myfile.txt echo $? 1
Now lets go one step closer to a more useful script. Lets say you want to do one thing if the file is found and then do something else if the file isn’t found.
Well for this we use an else in the IF.
if [ -f /foo/myfile.txt ] ; then echo "the file exists"; else echo "the file can not be found" fi
Now we get a echo if the file isn’t found.
We can also use a var for the file name in the script and make it a bit more interactive .
#!/bin/bash read -p "enter file name: " findFile if [ -f $findFile] ; then echo "the file exists"; else echo "the file can not be found" fi
Copy the above script and save it as a .sh file and then execute it, like:
Let me explain what this script does. The ‘ read -p “enter file name: “ ‘ is shown after running the scrip, you then just need to add the file name. this is then assigned to the defined ‘findFile‘. It is then used in the find command ‘ [ -f $findFile] ‘. If it is found then it will echo ‘ the file exists’ otherwise it will echo ‘ the file can not be found’.
But please note that this will find the file, or not, with an absolute path of the file. For example you can type myfile.txt and it will search for it in the same directory as the script is running. If you want to search for the file in another folder the the path must be added: