Linux check exist file

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.

Источник

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:

Читайте также:  16 bit windows subsystem как исправить

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.

Источник

How to Check if File or Directory Exists in Bash Shell

If you are working on a Bash script that interacts with files and directories, you might encounter a situation where you need to make sure that the file or directory exists. This helps avoiding possible errors for performing certain actions on a file that doesn’t exist.

In this tutorial, I’ll show you a couple of ways to check if file or directory exists in bash script or not. Let’s start with file first.

Check if file exists in bash script

The idea here is to use the -f operator that returns true only when it is a regular file (not directory).

Let’s say you want to check if file /home/user/my_file exists or not. Here’s how you can check with square brackets

But you won’t always get the file name before hand, will you? You can have it in a variable and if that’s the case, you can use it in this fashion.

Basically, what matters is the condition you use in the if command. It’s up to you how you want to use the if statement.

For example, you can write it with two square brackets, keep ‘then’ in the same line as ‘if’ with the help of semicolon like this:

or put the entire statement together like this:

Check file exists in bash with test

You can also use test in bash to see if file exists or not. It’s pretty much the same thing only that you don’t use the square brackets in the if statement:

You can also use the above code in single line like this:

Check if file doesn’t exist in bash script

What if it’s the other way round and you want to check if file does not exist in bash? You can use pretty much the same code as above by using the negation operator:

Now that you know how to deal with files, let’s move on to directories.

Check if directory exists in bash script

The code for checking directory is the same as the one you saw in the previous section. The only difference is that you’ll be using -d instead of -f. -d returns true only for directories.

You can also use test here:

Check if directory doesn’t exist in bash

You can use the negation again to check if directory doesn’t exist:

That’s it. That’s all you need to do for checking if a directory of file exists in bash shell or not.

I hope you find this bash tip useful. If you have any questions or suggestions, please feel free to leave a comment below.

Источник

Linux / UNIX: Find Out If File Exists With Conditional Expressions in a Bash Shell

W ith the help of BASH shell and IF command, it is possible to find out if a file exists or not on the filesystem. A conditional expression (also know as “evaluating expressions”) can be used by [[ compound command and the test ( [ ) builtin commands to test file attributes and perform string and arithmetic comparisons.


You can easily find out if a regular file does or does not exist in Bash shell under macOS, Linux, FreeBSD, and Unix-like operating system. You can use [ expression ] , [[ expression ]] , test expression , or if [ expression ]; then . fi in bash shell along with a ! operator. Let us see various ways to find out if a file exists or not in bash shell.

Syntax to find out if file exists with conditional expressions in a Bash Shell

The general syntax is as follows:
[ parameter FILE ]
OR
test parameter FILE
OR
[[ parameter FILE ]]
Where parameter can be any one of the following:

  • -e : Returns true value if file exists.
  • -f : Return true value if file exists and regular file.
  • -r : Return true value if file exists and is readable.
  • -w : Return true value if file exists and is writable.
  • -x : Return true value if file exists and is executable.
  • -d : Return true value if exists and is a directory.

Please note that the [[ works only in Bash, Zsh and the Korn shell, and is more powerful; [ and test are available in POSIX shells. Let us see some examples.

Find out if file /etc/passwd file exist or not

Type the following commands:
$ [ -f /etc/passwd ] && echo «File exist» || echo «File does not exist»
$ [ -f /tmp/fileonetwo ] && echo «File exist» || echo «File does not exist»

How can I tell if a regular file named /etc/foo does not exist in Bash?

You can use ! operator as follows:
[ ! -f /etc/foo ] && echo «File does not exist» Exists
OR

[[ example

Enter the following commands at the shell prompt:
$ [[ -f /etc/passwd ]] && echo «File exist» || echo «File does not exist»
$ [[ -f /tmp/fileonetwo ]] && echo «File exist» || echo «File does not exist»

Find out if directory /var/logs exist or not

Type the following commands:
$ [ -d /var/logs ] && echo «Directory exist» || echo «Directory does not exist»
$ [ -d /dumper/fack ] && echo «Directory exist» || echo «Directory does not exist»

[[ example

$ [[ -d /var/logs ]] && echo «Directory exist» || echo «Directory does not exist»
$ [[ -d /dumper/fake ]] && echo «Directory exist» || echo «Directory does not exist»

Are two files are the same?

Use the -ef primitive with the [[ new test command:

How to check if a file exists in a shell script

You can use conditional expressions in a shell script:

Save and execute the script:
$ chmod +x script.sh
$ ./script.sh /path/to/file
$ ./script.sh /etc/resolv.conf
To check if a file exists in a shell script regardless of type, use the -e option:

You can use this technique to verify that backup directory or backup source directory exits or not in shell scripts. See example script for more information.

  • 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

A complete list for file testing in bash shell

From the test command man page:

[ Expression ] Meaning
-b filename Return true if filename is a block special file.
-c filename Return true if filename exists and is a character special file.
-d filename Return true filename exists and is a directory.
-e filename Return true filename exists (regardless of type).
-f filename Return true filename exists and is a regular file.
-g filename Return true filename exists and its set group ID flag is set.
-h filename Return true filename exists and is a symbolic link. This operator is retained for compatibility with previous versions of this program. Do not rely on its existence; use -L instead.
-k filename Return true filename exists and its sticky bit is set.
-n filename Return true the length of string is nonzero.
-p filename Return true filename is a named pipe (FIFO).
-r filename Return truefilename exists and is readable.
-s filename Return true filename exists and has a size greater than zero.
-t file_descriptor Return true the filename whose file descriptor number is file_descriptor is open and is associated with a terminal.
-u filename Return true filename exists and its set user ID flag is set.
-w filename Return true filename exists and is writable. True indicates only that the write flag is on. The file is not writable on a read-only file system even if this test indicates true.
-x filename Return true filename exists and is executable. True indicates only that the execute flag is on. If file is a directory, true indicates that file can be searched.
-z string Return true the length of string is zero.
-L filename Return true filename exists and is a symbolic link.
-O filename Return true filename exists and its owner matches the effective user id of this process.
-G filename Return true filename exists and its group matches the effective group id of this process.
-S filename Return true filename exists and is a socket.
file1 -nt file2 True if file1 exists and is newer than file2.
file1 -ot file2 True if file1 exists and is older than file2.
file1 -ef file2 True if file1 and file2 exist and refer to the same file.

Conclusion

You just learned how to find out if file exists with conditional expressions in a Bash shell. For more information type the following command at shell prompt or see test command in our wiki or see bash man page here:
test(1)

Источник

Читайте также:  Top linux distros 2021
Оцените статью