Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • Using if statement
  • Using the test command
  • Check if file does not exist
  • Check if multiple files exist
  • Other Primary Expressions
  • Conclusion

Bash Scripting: How to Check if File Exists

PreviousHow to Read CSV File in BashNextBash If Else Statements: Examples and Syntax

Last updated 1 year ago

Files are resources that store information in the form of data, configurations, settings or commands and are identified by a unique name and type. We often want to examine the status of such files, whether they exist or are empty.

In this guide, we will focus on the different options to check if the file exists in Bash.

Using if statement

We have different options available with us to see if a file exists.

-a option

It returns true if the file exists.

Syntax

[ -a FILE ]

Example

if [ -a sample.txt ]; then echo true; else echo false; fiif [ -a alpha.txt ]; then echo true; else echo false; fi

The -a flag checks if the specified file exists. If it does, a zero return status is generated and the if condition of the code is executed. In the second case, a non-zero return status results in the execution of the else part.

-e option

It returns true if the file exists, regardless of the file type.

Syntax

[ -e FILE ]

Example

if [ -e sample.txt ]; then echo true; else echo false; fiif [ -e alpha.txt ]; then echo true; else echo false; fi

As we are now aware that Linux treats everything as files, we can use this option with any files as well as directories. A true will be printed if the file or the directory exists and otherwise it will display false as the output.

-f option

It returns true if the file exists and is a regular file.

Syntax

[ -f FILE ]

Example

if [ -f sample.txt ]; then echo true; else echo false; fiif [ -f alpha.txt ]; then echo true; else echo false; fiif [ -f atlas ]; then echo true; else echo false; fi

Regular Linux files are the files that may include text, data, information, piece of code or program instructions. This flag is widely used by Bash programmers to make the code flow in such a way that tasks get performed only if the file exists. Here, in our case, too, we are checking if the regular file exists and printing true if it does.

Using the test command

We have a Bash utility named 'test', that helps determine whether a file exists. Its alias is square brackets ([ ]) We can also take the help of double square brackets ([[ ]]).

Syntax:

test expression
[ expression ] 
[[ expression ]]

Example:

#!/bin/bash File=/etc/passwd echo "-----------Using test-----------"if test -f "$File"then echo "true" fi echo "-----------Using [ ]-----------"if [ -f "$File" ]then echo "true" fi echo "-----------Using [[ ]]-----------"if [[ -f "$File" ]]then echo "true" fi echo "-----------Without if-----------"test -f $File && echo "true" echo "-----------Using [ ] without if-----------"[ -f "$File" ] && echo "true" echo "-----------Using [[ ]] without if-----------"[[ -f "$File" ]] && echo "true"

We can couple it with the Bash if statement to develop conditions. It is usually employed for conditional branching and caters to numerical or string comparisons. However, we can determine the status of a file as well. This check is widely used to redirect outputs only if the file exists or to verify if the file was downloaded. We can also use the shorthand technique if we do not wish to use the if statement.

Check if file does not exist

We can negate the expression by using the exclamation mark (!). It acts as the logical not operator.

Example:

if [ ! -e sample.txt ]; then echo "File does not exist"; else echo "File exists"; fiif [ ! -e alpha.txt ]; then echo "File does not exist"; else echo "File exists"; fiif [ ! -f sample.txt ]; then echo "File does not exist"; else echo "File exists"; fiif [ ! -f alpha.txt ]; then echo "File does not exist"; else echo "File exists"; fi

This approach works exactly the same way as above. However, here it checks if the file does not exist because of the presence of the ! operator. If it doesn’t, the expression becomes true and the then block gets executed, which will print the desired output. However, if the file exists, the return status is non-zero and, as expected, the else part of the code executes.

This check is often used by developers to create a regular file only if it doesn’t exist and then, maybe do some operations like append to it.

Example:

File=/home/ubuntu/exampleif [ ! -f "$File" ]then touch $File echo " Appending this line to $File" >> $Filefi

We are checking if the given file exists or not. Since there is the negation (!) operator and as the directory doesn’t exist, it will execute the then block of the code. This will enable the touch command to execute which will create the file. If we don't want the modification time of the file to be changed by touch we can use pass the -a parameter with the touch command to make touch only alter the access and the change time.

Check if multiple files exist

We can also test if multiple files exist in a single check.

Example:

[ -f sample.txt -a -f sample1.txt ] && echo "Both the files exist"[[ -f sample.txt && -f sample1.txt ]] && echo "Both the files exist"if [ -f sample.txt -a -f sample1.txt ]; then echo "Both the files exist"; fiif [[ -f sample.txt && -f sample1.txt ]]; then echo "Both the files exist"; fi

Instead of writing complex nested if conditions, Bash ensures that we can verify if multiple files exist using a single check using the and operator. This operator has to be used differently with the expression we use. If we use the single square brackets to carry out the check, we have to use -a to join two conditions. Similarly, for double square brackets, we must use the && symbol as the and operator.

Other Primary Expressions

With Bash, we can also check for specific types of files. The table below lists the operations we can perform on files.

Options
Description

[ -a FILE ]

Returns true if FILE exists.

[ -b FILE ]

Returns true if FILE exists and is a block special file.

[ -c FILE ]

Returns true if FILE exists and is a character special file.

[ -d FILE ]

Returns true if FILE exists and is a directory.

[ -e FILE ]

Returns true if FILE exists.

[ -f FILE ]

Returns true if FILE exists and is a regular file.

[ -g FILE ]

Returns true if FILE exists and its SGID bit is set.

[ -h FILE ]

Returns true if FILE exists and is a symbolic link.

[ -k FILE ]

Returns true if FILE exists and its sticky bit is set.

[ -p FILE ]

Returns true if FILE exists and is a named pipe (FIFO).

[ -r FILE ]

Returns true if FILE exists and is readable.

[ -s FILE ]

Returns true if FILE exists and has a size greater than zero.

[ -u FILE ]

Returns true if FILE exists and its SUID bit is set.

[ -w FILE ]

Returns true if FILE exists and is writable.

[ -x FILE ]

Returns true if FILE exists and is executable.

[ -O FILE ]

Returns true if FILE exists and is owned by the effective user ID.

[ -G FILE ]

Returns true if FILE exists and is owned by the effective group ID.

[ -L FILE ]

Returns true if FILE exists and is a symbolic link.

[ -N FILE ]

Returns true if FILE exists and has been modified since it was last read.

[ -S FILE ]

Returns true if FILE exists and is a socket.

Conclusion

  • We have different methods to examine the status of the file.

  • We can use the ! operator to check if the file does not exist.

  • We can test if multiple files exist in a single check.

using -e option check if file exists
using -a option check if file exists
Check if file does not exist
check if multiple files exist
using -f option check if the file exists
using test command check file exists