How to check if a directory exists in Bash

Bash is a powerful tool you can use to chat with your computer, widely used in Linux distributions and macOS. Bash scripts help you teach your computer to do tasks without manual intervention.

Ready for some fun learning? Let's delve into the world of directories and Bash!

Deciphering directories

Think of a directory as a home for your files and other directories. If you're familiar with using a computer, you've definitely come across directories/folders in your graphical user interface. But when we're using Bash, we'll be using commands instead of point-and-click.

The test keyword

The key to checking if a directory exists, we use the test command. This handy tool allows you to check file types and compare values, and it's crucial to Bash scripting.

To ask test about a directory, we use -d (which stands for directory) followed by the directory path. Let's see it in action:

Terminal 1
Terminal
Loading...

This line will whisper a secret to Bash: 'zero' if the directory exists (which is Bash's way of saying "true") and 'non-zero' if it doesn't (Bash for "false"). But Bash is a good secret-keeper, and it won't display this result. So, we're going to use if statements to reveal it.

Interrogating with the if statement

The if statements are Bash's detectives. They investigate a condition and execute a code only if the condition turns out to be true. If the condition is false, they simply move on.

Let's see how to use if statement with the test command:

Terminal 1
Terminal
Loading...

In this script, if the directory exists, Bash will print "The directory is real!". If it doesn't, it will print "The directory is a myth.".

The use of []

Bash has a little magic trick up its sleeve – the [] (brackets), which act as a shortcut for the test command. Here's how you can use it:

Terminal 1
Terminal
Loading...

Like the previous script, this one also confirms or denies the existence of the directory.

Wrapping up

And there you have it! checking if a directory exists in Bash is a piece of cake with the test command and the if statement. As you delve deeper into Bash scripting, you'll see that these tools are incredibly versatile and form the building blocks for many more tasks.

If you're finding some errors or feeling stuck, remember, that's part of the journey. Take a breather, go over your script, and don't hesitate to give it another shot. Keep the coding spirit alive and have fun scripting!

Free Resources