How To Check If A File Exists In Bash

How To Check If A File Exists In Bash

When scripting in Bash, users often come across situations where they need to check whether a file or directory exists or not.

The if and test commands are used in conjunction to check whether a file exists or not in Bash. You’ll typically use expressions like -e or -f to check a file’s existence, whereas -d is used in the case of directories.

In addition to further info on these, we’ve also detailed how to check if a file exists using wildcards and how to exclusively check if a file doesn’t exist in this article.

Check If File or Directory Exists

First, let’s talk about the primary expressions, i.e., primaries. You can use the man test command to check test’s man page for the full list of primaries, but here are the most commonly used ones:

ExpressionDescription-a FILEFILE exists. -d FILEFILE exists and is a directory.-e FILEFILE exists.-f FILEFILE exists and is a regular file.-r FILEFILE exists and is readable.-x FILEFILE exists and is executable or searchable.

Let’s start with something basic. In the following example, we store the file’s path in $FILE. From the table above, -e means that if FILE exists is true, then the $FILE exists output will be echoed. If FILE doesn’t exist, then the $FILE doesn’t exist will instead be the output that’s echoed.

FILE=/file/path
if [[ -e "$FILE" ]]; then
echo "$FILE exists."
else
echo "$FILE doesn’t exist."
fi

How To Check If A File Exists In Bash

You could do the same thing more efficiently as such:
test -e /file/path && echo “File exists.” || echo “File doesn’t exist.”

How To Check If A File Exists In Bash

You could also use wildcard characters for this:
[ -e /file/path ] && echo “File exists.” || echo “File doesn’t exist.”

How To Check If A File Exists In Bash

You would use the -d expression to check if a directory exists or not:
[ -d /directory/path ] && echo “Directory exists.” || echo “Directory doesn’t exist.”

How To Check If A File Exists In Bash

Check If A File Doesn’t Exist

If you’re only trying to check if the file doesn’t exist, you can use the NOT operator (!) as such:
if [ ! -e /file/path ]; then
echo "File doesn’t exist."
fi

But once again, you can do the same thing more efficiently as such:
[ ! -e /file/path ] && echo "File doesn’t exist."

How To Check If A File Exists In Bash

Check if Multiple Files Exist

If you’re trying to check whether multiple files exist or not at once, you can use the -a expression or the && operator.

Using -a

The first method is as such:
if [ -e /file/one -a -e /file/two ]; then
echo "Both files exist."
fi

Whereas a more efficient variant would look like this:
[ -e /file/one -a -e /file/two ] && echo "Both files exist."

How To Check If A File Exists In Bash

Using &&

The first method is as such:
if [[ -e /file/one && -e /file/two ]]; then
echo "Both files exist."
fi

An equivalent variant would look like this:
[[ -e /file/one && -e /file/two ]] && echo "Both files exist."

How To Check If A File Exists In Bash

Check If One of Two Files Exists

If you’re trying to check if one of two files exists, you could use the following command:

if [ -f /file/path ] || [ ! -f /file/path ] ; then echo Exists; fi

How To Check If A File Exists In Bash

If you’re trying to check if one of two files doesn’t exist, you could instead apply ! to one of the file paths as such:
if [ -f /file/path ] || [ ! -f /file/path ] ; then echo Missing; fi

How To Check If A File Exists In Bash

News Related

OTHER NEWS

Maruti Grand Vitara Delta MT Mid Variant – First Look Walkaround

Maruti Grand Vitara SUV will be launched soon in India to rival Creta and Seltos Maruti Grand Vitara Delta Mid Variant For the last couple of years or so, Maruti ... Read more »

Post Office Scheme: Here's HOW to get more than Rs 10 lakh in just 3 years

New Delhi: Every investor wants their investment completely safe and with maximum return. There are many schemes available in the market which is best for investment. Here is one of the ... Read more »

How to keep your potatoes fresh: 'Prevent them from sprouting too quickly'

Potatoes The content creator, known as Neat Caroline, is a professional organiser from New York City. She has almost 200,000 followers on her TikTok account and has amassed three million ... Read more »

Most Keurig Machines Are Pretty Nasty Inside: Here's How to Clean Yours

Keeping your Keurig coffee maker clean will ensure that it makes the best brew possible. Brian Bennett/CNET Putting your Keurig to work morning after morning will inevitably lead to some gunky buildup ... Read more »

Destiny 2 – Hotfix 6.2.0.6 Fixes Missing 120Hz Mode on PS5 and Xbox Series X

Various issues with the King's Fall raid, seasonal mods stacking with each other, Touch of Malice, and more have also been fixed. Read more »

Comments on Your Physical Appearance Can Hurt — Here’s How to Handle It

A woman sits on a chair with her hands over her face and body In my first year of university, I had to take a picture for a press card ... Read more »

OnePlus Nord Watch Full Specifications Leaked Ahead of India Launch: All You Need to Know

The OnePlus Nord Watch is expected to be launched on September 28th. Read more »

Why I Am Buying a Google Pixel 6a During Flipkart Big Billion Days Sale, Despite Its Flaws

Sometimes, it’s okay to buy phones just because they are fun Read more »

Top 10 200cc To 500cc Motorcycles Jul 2022 – Classic, Bullet, Pulsar, Dominar

Motorcycles in 200-500cc range posted a 6.87 percent YoY growth in July 2022 while MoM sales dipped 7.04 percent with Royal Enfield 350 cc models taking top spots New Bajaj ... Read more »

Why Americans Can’t Agree on How to Handle the Migrant Crisis

Dominic Chavez for The Washington Post via Getty Last week’s flight of about 50 migrants from San Antonio to Martha’s Vineyard, orchestrated by Florida’s Republican Gov. Ron DeSantis, was an ... Read more »

NASA's DART Mission to Slam Into Asteroid on Sept. 26: How to Watch

It is a big day for the National Aeronautics and Space Administration (NASA) on Monday, September 26, as it is the day when its Double Asteroid Redirection Test (DART) mission ... Read more »

How to clean a glass stovetop: 4 easy steps for a mirror-like shine

null A smooth, contemporary glass finish always looks sleek and stylish, and knowing how to clean a glass stovetop will ensure it stays looking that way without running the risk ... Read more »

Is a fact always true? A philosopher explains how to spot the difference

Is a fact always true? A philosopher explains how to spot the difference Astronomers once believed the Sun revolved around the Earth. In the 19th century, scientists thought the shape ... Read more »

Nothing Ear Stick case design revealed, it’s not square-shaped

The awe-inspiring Nothing Ear Stick earbuds’ charging case design has been revealed at the London Fashion Week. Nothing is sparing no effort to create hype around its upcoming earbuds. In ... Read more »

How to make the air fryer cheese toastie recipe declared 'banging!' - recipe

An air fryer toastie and an air fryer machine TikTok user Lee Wakefield has sent users of the popular social media app wild trying out an air fryer toastie hack. ... Read more »

Xiaomi 12T 5G series tipped to get a new Lunar Silver color option

The Xiaomi 12T and Xiaomi 12T Pro smartphones’ Lunar Silver color variant has surfaced online ahead of an official unveiling. The Xiaomi 12T 5G series will arrive in the global ... Read more »

Arknights Anime Adaptation Wears Mobile RPG Origin Proudly in New Trailer

The anime adaptation of the Arknights mobile RPG has gotten a new trailer today that shows off the colorful characters that inhabit the world. If you were shown this trailer ... Read more »

Glass Onion: A Knives Out Mystery Exclusive Clip Teases the Plot’s Deadly Puzzle

Glass Onion, the sequel to 2019’s whodunnit mystery Knives Out, has just gotten an exclusive clip released online after being originally showcased during Netflix’s TUDUM presentation. The clip looks to ... Read more »

Square Enix Reveals Opening Cutscene of Engage Kill, New Game Set in the World of Engage Kiss Anime

The Engage Kiss anime has wrapped up, but fans of its world will have a new experience to explore thanks to Square Enix’s Engage Kill. Engage Kill is a new ... Read more »

Toxic beauty standards and how to overcome them

Toxic beauty standards and how to overcome them “Do I look okay?”, “Is my hair fine”? “Is my skin clear?”, are some of the many questions people ask themselves every ... Read more »

Netflix's Creepy New Series The Watcher Gets First Trailer

Netflix is bringing the true story of a nightmare home from Ryan Murphy. Read more »

Vivo X Fold+ 5G spotted on Wireless Power Consortium website

The Vivo X Fold+ 5G foldable smartphone has been spotted on the Wireless Power Consortium with an image that reveals key details. The 5G-ready foldable phone will launch in China ... Read more »

Guillermo Del Toro Gives First Behind The Scenes Look At Netflix's Pinocchio

The Oscar-winning director gives fans a first look at the different types of puppets that were used to bring the classic to life. Read more »

8 Best Live TV Apps for Android TV 2022: Disney+Hotstar, YuppTV, Voot, and More

Check out the list of the best apps for live TV on Android TV. Read more »

Every woodworker should know how to mill their own boards

Flat, square, and straight planks will make your DIY projects much easier. You don’t need a fancy woodshop like this guy to ensure all your planks are straight. If you’ve ... Read more »

How to Create Apple ID on iPhone, Mac and PC

If you do not have an Apple ID or want to create a New Apple ID, you can find below the steps to create Apple ID on iPhone, Mac and ... Read more »

How To Set Reminders On Windows PC

When your plate is full, it’s easy to forget things, but fortunately, Windows provides several options to establish reminders. So that you never forget to submit a paper on time ... Read more »

How To Fix NBA 2K23 Keeps Crashing On PC

The highly anticipated newest installment of the NBA 2K series, NBA 2K23, has finally been released. Some players have complained that the game frequently crashes on their computers. The 5 ... Read more »

Disabled woman fighting cancer was 'carried down stairs of East London flat' after council 'didn't fix lift in time for chemotherapy'

A Walthamstow resident who has stage 4 breast cancer has criticised Waltham Forest Council for “failing to deal with a lift” in her apartment on Wood Street, which she claims ... Read more »

Netflix Drops Hints at Future Outer Banks Drama In New Season 3 Teaser

In the most recent Netflix Tudum showcase, a new teaser trailer was released for the upcoming third season of the Outer Banks series. Outer Banks first premiered in April 2020, ... Read more »

How to complete all deeds in Sea of Thieves: The Siren’s Prize

Screenshot by Gamepur Earning both rewards from The Siren’s Prize in Sea of Thieves requires you to complete not only the Adventure but also all eight of its Deeds as ... Read more »

How to cook Frozen Jalapeno Poppers in Air Fryer!

Jalapeno Poppers in Air Fryer Frozen Equipment Needed How to make Frozen Jalapeno Poppers in the Air Fryer Recipe Tips Great Air Fryer Recipes How to cook Frozen Jalapeno Poppers ... Read more »

Microsoft Forms vs Google Forms: Which is better?

Microsoft Forms and Google Forms are two of the most used tools for creating online forms, surveys, quizzes, and more. You can also use any of these tools to create ... Read more »

What channel is Floyd Mayweather vs. Mikuru Asakura on tonight? How to watch, buy 2022 boxing exhibition fight

What channel is Floyd Mayweather vs. Mikuru Asakura on tonight? How to watch, buy 2022 boxing exhibition fight Floyd Mayweather will be teaming up with RIZIN once again, as he ... Read more »

Lost Judgment: How To Change Time Of Day

Lost Judgment: How To Change Time Of Day Lost Judgement sometimes requires players to wait for a specific time of day in order to trigger an event or continue a ... Read more »

What is Gadget mode in Slime Rancher 2 and how to use it

Screenshot by Pro Game Guides While Slime Rancher 2 explains how to place slime corrals and chicken coops, it doesn’t clarify how to use Gadget Mode. Gadget Mode is a ... Read more »

How to unlock the Bruen .45 Handgun in Modern Warfare 2 Beta

Screenshot by Pro Game Guides Call of Duty: Modern Warfare 2 Beta only offers a small selection of weapons to play with, however, there is a glitch using which you ... Read more »

What time is Floyd Mayweather’s fight tonight? Ringwalks, running order, streaming, how to watch Mayweather vs. Mikuru Asakura

What time is Floyd Mayweather’s fight tonight? Ringwalks, running order, streaming, how to watch Mayweather vs. Mikuru Asakura The Floyd Mayweather Jr. exhibition world tour continues on Sunday as the former ... Read more »

Mayweather vs Asakura LIVE: Stream, latest updates and how to watch fight

Follow live updates as the American takes on the mixed martial artist in an exhibition boxing match Read more »

I worked as a butler for King Charles and here’s how to eat your favourite foods in high society

DO you know the “proper” way to eat a Pot Noodle? An etiquette expert revealed on TikTok how to eat the tasty snack in polite company, with her video clocking ... Read more »
Breaking thailand news, thai news, thailand news Verified News Story Network