With 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
#!/bin/bash file="/.config/backup.cfg" if [ ! -f "$file" ] then echo "$0: File '${file}' not found." fi
[[ 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:
## first compare /etc/resolv.conf with /etc/resolv.conf ## [[ /etc/resolv.conf -ef /etc/resolv.conf ]] && echo "Same files" || echo "Noop" ## now compare /etc/resolv.conf with /etc/passwd ## [[ /etc/resolv.conf -ef /etc/passwd ]] && echo "Same files" || echo "Noop"
How to check if a file exists in a shell script
You can use conditional expressions in a shell script:
#!/bin/bash FILE="$1" if [ -f "$FILE" ]; then echo "File $FILE exist." else echo "File $FILE does not exist" >&2 fi
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:
#!/bin/bash FILE="$1" [ "$FILE" == "" ] && { echo "Usage: $0 filename"; exit 1; } if [ -e "$FILE" ]; then echo "File $FILE exist." else echo "File $FILE does not exist" >&2 fi
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.
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)
🐧 Get the latest tutorials on Linux, Open Source & DevOps via:
- RSS feed or Weekly email newsletter
- Share on Twitter • Facebook • 40 comments... add one ↓
Category | List of Unix and Linux commands |
---|---|
File Management | cat |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Network Utilities | 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 • jobs • killall • kill • pidof • pstree • pwdx • time |
Searching | grep • whereis • which |
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 |
What is the purpose of ” . ” / dot before ~/.bashrc in the script below.
See it in multiple system script files which have “if file exists” check.
$ cat ~/.bash_profile
Thanks in advance.
It will execute commands from a file in the current shell. In other words run commands from ~/.bashrc file.
On MacOS using fish shell, your examples helped me build my own cmd one liner
for line in (cat test.txt); [ -f $line ] && echo "$line exist" || echo "$line does not exist" ; end
very useful,,,thanks a lot.
i want to check if the file exists in a folder:
if exists(delete the file in the folder)
else
create a new file in the same name.
I tried the above codes which dint work for me.. any help would be of great help..
why use >&2
“File does not exists” should be “File does not exist” right?
Very useful is also the test parameter “-s” which checks if a file exists and has a size greater then zero.
I need to check if in
1.example1.sh test.log exists
if 1 is yes then execute 2 else execute 5
2. get the current date from test.log file
3. get current system date
4. if date in step 2 + 1 day <=date in step 3 then step 5 else step 6
5. execute example2.sh
6.end
example2.sh
writes to test.log
and also contains current date and current time
Not Working for me for the below code
#!/bin/bash
FILE=$1
if [ ! -f $FILE ];
then
echo “File $FILE does not exists”
fi
How are you running the script?
I have a file with date and time. but I want to check with date part only file exist or not without changing the file.
Can any one pleae help me.
Can we find content in file with if condition, for an example if ‘abc’ is there in xyz file or not.
Regards,
Manoj
i need shell script where the i need to connect from one server to another server…
and check for file *.mediate.log in path /home/apps/ and if found it need to execute a script prescript.sh in the same path and return a status to the server…and if the files doesn’t exist it shud return another status…and if the job fails becoz of any resin it need to return another status…
Can you please help me with this ASAP…very urgent
Thanks for the script, it was very useful.
if [ -e filename ] works for me and checks fine ONLY when I’m logged in as a power broker. It doesn’t test when I log in as a normal user or call the script from a different scheduling tool.
Please help me ASAP
That was a great help, I needed a script to check if the .parentlock file was present in the Thunderbird profile directory and then delete it if it was.
Worked first time 🙂
you could also have done the following:
find /home/username/thunderbird-directory/ -iname .parentlock -ok rm {} ;
it’ll find the file and attempt to remove it, but will ask you first… if you need it to remove it right away, replace -ok with -exec
I want to check file that i fetching is complete or not, if file is still copying than wait for few minutes, can this things possible, Reply me Please!!!
i need to check all the files in the current directory and display them.how can i do this?
cd /path/to/directory
for i in $(ls -1 *)
do
if [ -f $i ] ; then
ll $i
else
echo “$i is not a file”
fi
Hi,
I have /media/USBDisk0 and that the mount point for my USBDisk.
And a hard link named /media/TheData/Data -> /media/USBDisk0/Data
When the USB is mounted, the hard link is OK, but If something fail, the hard link is broken…. Can use the if to test the hard link?
Hi,
I need to check if a file with the current date exists in a folder. How would I do that?
ls D
blah blah blah
drwx—— Program Files
if -d D/Program Files returns FALSE
It would be nice if I could find some way of successfully testing for names with spaces 🙁
Cheers,
Wol
Try ls -1D (that’s ls -‘ONE’ -D)
the only thing i can say is that –
if statement does’nt allow wild card, you have to think a work around for this
I need the shell script to check whether the file exist or not
and whether the format of the file is .dat or not
expecting the help ASAP…pls
Did someone figure this out?
Take a look at file command. It can determine file type.
I want to test if any file ending in *.DATGO exists.
Do you always have to use the exact name of the file?
For me, it only works without variables, like
if [ -f /home/user/hey.jpg ]; then
….
else
….
fi
Worth trying.
How to check some set of files in the following directory and do the process.
my statement following is not working: pls explain
if [ -f “$ROOT/abc/files/CUST*” ]; then
echo “inside customer file exists”
else
echo “No customer file exists”
fi
CUST is the post fix of the files, expected to have more than 1 file on some days.
I just hacked this together. I plan to use it for my other scripts. The exit statements make the script exit with a 0 (bash standard for successful completion) or a 1 (non-zero is the bash standard for a failed action)
Just this much will do,
#!/bin/bash
FILE=$1
[[ -f $FILE ]]
Bash knows the NOT procedure for IF. So No ELSE would be used. watch the !
Hello Volks:
I would like to look for a File: if it exists – AND – it´smaller (lt/gt) than 1000000, then … echo ” File too small” , return 1 … and so on:
#!/bin/bash
FILE=nec2.txt
if -f [ “$FILE” ] && -f [ “$FILE” -lt 1000000 ] ;
then
echo “File $FILE too small”
else
echo “File $FILE does not exists”
fi
-rw-rw—- 1 cas lokus 31626 2008-12-15 14:00 xnec2.txt
I use linux 2.4.21-278-smp
Can you please help there ? Pleas reply to donpetrus@hotmail.com
Many thanks in advance – Petrus
DatePart=`date ‘+%m%d%Y`
FileName =DataFile_${DatePart}.csv
I need to check a file on daily basis that is created by anotehr process. The file format is:
DataFile_MMDDYYYY.csv
So, I need to get today’s date in MMDDYYYY format, concate that with a string variable, FileName = “DataFile_” + DatePart + “.csv”
Then look for that FileName file if exists then run a command (sas sendemail.sas).
How can I achieve that? Thanks.
script was very userful
For me the if statement only works when using the FILE var with quotes like this:
if [ -f “$FILE” ];