Check if the file exists linux

Bash Shell: Check File Exists or Not

H ow do I test existence of a text file in bash running under Unix like operating systems?

You need to use the test command to check file types and compare values. The same command can be used to see if a file exist of not. The syntax is as follows:

The following command will tell if a text file called /etc/hosts exists or not using bash conditional execution :

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

The same code can be converted to use with if..else..fi which allows to make choice based on the success or failure of a test command:

File test operators

The following operators returns true if file exists:

(Fig.01: File test operators taken from bash man page)
The syntax is same (see File operators (attributes) comparisons for more info):

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Thank you for the trick!

thanks much for that useful information

i made a linux script which receives as first argument a path to a directory. I don’t know the path. And i want to check if “file.txt” exists at that certain path . For example :

if [ -e $1/file.txt ];then echo HAHA fi

if you use -f with *.sock files it always says “the file does not exist”. when I use -e it worked 🙂

What if I want to test for the existence of any files with a particular filename extension? Is there a simple way to do that? I’ve trying to use the return status of the ls command but I seem to be getting the syntax a bit wrong.

You can use wildcard. Ex:
[ -e *”.extension” ]

(don’t forget to have a space character before the operator and before the closing branch, it took hours of my time to recognize this 😐 )

Can I mix the operator?
like:
if [-xw filename]
(Checking the existence of the file that executable and writable)

i want to write script to copy a some of the files inside directory to specified location(for example i have one directory, this containes 1000 image file. then i need pick only 100 image file from 1000 image file. also i have a list of images which i need to copy (i made one file).

can anyone help on this(please forword to my mail)

in my script I have[ $FILE ! = “”] ..what does it mean…

FILE has lot ma y rows extracted file names from database.

Источник

Bash: Test If File Exists

While creating a bash script, it is commonly helpful to test if file exists before attempting to perform some action with it.

This is a job for the test command, that allows to check if file exists and what type is it.

As only the check is done – the test command sets the exit code to 0 ( TRUE ) or 1 ( FALSE ), whenever the test succeeded or not.

Also the test command has a logical “not” operator which allows to get the TRUE answer when it needs to test if file does not exist.

Cool Tip: Create a clever bash script! Make it do more tests! Check easily whether a string exists in a file! Read more →

Bash Shell: Test If File Exists

Run one of the below commands to check whether a file exists:

Test if the file /etc/passwd exist ( TRUE ):

Test if the file /etc/bebebe exist ( FALSE ):

Test if the file /etc/bebebe does not exist ( TRUE ):

If File Exists, Then …

We usually test if a file exists to perform some action depending on the result of the test.

Maybe if file doesn’t exist – there is no sens to move forward and it is required to break the script or whatever.

In the examples below, lets print corresponding messages depending on the results of the test command.

Cool Tip: The CASE statement is the simplest form of the IF-THEN-ELSE statement! If you have many ELIF elements – it is better to use the CASE ! Read more →

Test if the file /etc/passwd exists and print a message if it is TRUE :

Test if the file /etc/bebebe does not exist and print a message if it is TRUE :

Test if the file exists and print a corresponding message in the each case:

Bash Script: Test If File Exists

Create an empty checkfile.sh file with the touch checkfile.sh command.

Make it executable with chmod +x checkfile.sh .

Open the checkfile.sh with a text editor and put the following code:

Cool Tip: A good bash script prints usage and exits if arguments are not provided! It is very simple to configure! Read more →

Save and execute the script as follows:

Test If File Exists And It Is …

In the examples above with the -f operator we only check whether a file exists and it is a regular file.

Here are some other useful options that can help to check whether a “file” exists and has specific permissions or it is a symbolic link, socket or a directory:

Option Description
-e Test if file exists, regardless of type (directory, socket, etc.)
-f Test if file exists and is a regular file
-r Test if file exists and read permission is granted
-w Test if file exists and write permission is granted
-x Test if file exists and execute permission is granted
-L Test if file exists and is a symbolic link
-S Test if file exists and is a socket
-d Test if directory exists

Run man test to see all available operators.

Источник

How to check if a File exists in bash

How to check file existence using bash scripting:

1) By entering the file name in the terminal:

Firstly, we need to create a bash script file, use the below-mentioned command:

The name of the file I created is “testfile.sh”, the “.sh” extension indicates the shell script file:

Open the “testfile.sh” in any text editor. Then write the script, save it by pressing “save”.

One way is to find a file by asking for a filename from the user in the terminal.

Use “-f” to check the file’s existence.

Write the below script:

Go back to the terminal and run the file to print output:

Permission denied message would be displayed in the terminal.

Make it executable by executing the below-mentioned command:

Enter the file name, and it will print the output:

2) By entering the file name while writing the script:
Another way to find a file by giving the file name while writing the script. We have three ways to check the availability of the file. The first one is using the “test” command, the second is using “if” with an expression in square brackets, and the third is also with “if” but double square brackets as indicated below:

  1. “test EXPRESSION.”
  2. “if [ EXPRESSION ]”
  3. “if [[ EXPRESSION ]]”

Let’s understand it with examples:

1) test [ Expression ]
Copy the given script and paste it into the editor, save it:

Output:

As there is no such file in my directory, therefore the code displays the “File is not found” message.

2) if [ Expression ]

Copy the following script to check the if file exists or not:

Output:

3) if [[ Expression ]]

Copy the below-written script and paste it on the terminal:

Output:

To check directory:

3) By entering the directory name while writing a script

Use the “-d” flag to check the existence of a directory.

In the below-mentioned script, “dir11” is the variable in which you store the file the one you are finding; in this example, I want to check directory name “testDir” exists or not.

Output:

2) By entering the file name in the terminal:
When you run the command in the terminal to check whether the directory exists or not, you are required to enter the directory name that you are searching for:

Output:

Checking the file without using the “if” statement:

The “test” command can be executed without the “if” statement. It will only display output if the file exists; else, there would be no output:

Output:

Checking the directory without using the “if” statement:

Use the below-mentioned statements to check a directory exists or not:

Output:

Checking multiple files/Directories:

1) Checking multiple files with “if” statements:
Use the “-a” flag to check the existence of various files instead of using nested “if/else” statements:

Output:

2) Checking multiple files without using the “if” statement:
Use the following statement to check multiple files simultaneously 1without using “if”:

Output:

Conclusion:

This article has shown how to use bash scripting to check a file or a directory. We used different options to check the availability of a file. Firstly, we use the “test” command with different flags. Then we learned the usage of “if”, nested “if-else,” and without the “if” statements to check the file or directory. We also looked over how to check multiple files or directories.

About the author

Aqsa Maqbool

As a Software engineer, I am passionate to write about various IT related
articles but have deep interest in Linux. I spend most of my time reading Linux related blogs and IT related books. I want to serve the world with my writing skills.

Источник

Читайте также:  Operating systems windows linux unix
Оцените статью