Linux test file exist

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?

Читайте также:  Как форматировать диск через терминал mac os

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.

Источник

How to check if a file exists in a shell script

I’d like to write a shell script which checks if a certain file, archived_sensor_data.json , exists, and if so, deletes it. Following http://www.cyberciti.biz/tips/find-out-if-file-exists-with-conditional-expressions.html, I’ve tried the following:

However, this throws an error

when I try to run the resulting test_controller script using the ./test_controller command. What is wrong with the code?

6 Answers 6

You’re missing a required space between the bracket and -e :

Here is an alternative method using ls :

If you want to hide any output from ls so you only see yes or no, redirect stdout and stderr to /dev/null :

The backdrop to my solution recommendation is the story of a friend who, well into the second week of his first job, wiped half a build-server clean. So the basic task is to figure out if a file exists, and if so, let’s delete it. But there are a few treacherous rapids on this river:

Everything is a file.

Scripts have real power only if they solve general tasks

To be general, we use variables

We often use -f force in scripts to avoid manual intervention

And also love -r recursive to make sure we create, copy and destroy in a timely fashion.

Consider the following scenario:

We have the file we want to delete: filesexists.json

This filename is stored in a variable

We also hava a path variable to make things really flexible

So let’s see if -e does what it is supposed to. Does the files exist?

However, what would happen, if the file variable got accidentally be evaluated to nuffin’

What? It is supposed to return with an error. And this is the beginning of the story how that entire folder got deleted by accident

An alternative could be to test specifically for what we understand to be a ‘file’

So the file exists.

So this is not a file and maybe, we do not want to delete that entire directory

Источник

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)

Источник

Читайте также:  Свежие активаторы для windows 10
Оцените статью