Check directory linux command

Bash Check If Directory Exists

Directories and folders are the main and quite important parts of any operating system. Without the directories and files, our system doesn’t get completed. The directories are used to store the sub-folders and files that hold data in them for security and personal work. Within the Linux operating system, we have also got the same file system i.e., directories and sub-folders. Bash programming came up with some of the very simple commands and statements to check if the specific directory of a file exists in our system or not. Therefore, we have decided to write this article to check if the directory exists in our Linux system or not.

Example 01: Check If File Exists

Let’s get started with the basic example. We will be having a look at checking a simple file in our Linux system first i.e., if exists or not. Therefore, we have been creating a new text type file named “new.txt” within Ubuntu’s home folder with the “touch” instruction. We have added a one-line text in the file and displayed it on the shell using the “cat” instruction shown below. The output of the below-stated command is attached in the image.

Now, it’s time to create a new bash file with the “touch” instruction named “direc.sh” as below. We need to open this empty file to start coding in it. For this, we have been using the “nano” instruction to launch it within the GNU Nano editor. The output of the below-stated command is attached in the image.

Now, the empty file has been opened in the nano editor. Within the first line of code, we have initialized a file variable “F” holding a path to a file “new.txt” as “/home/linux/new.txt”. The “if-then” statement of bash has been utilized here to check if the file “new.txt” exists or not. The “if” clause is started with the keyword “test” followed by the flag “-f” for files. Within inverted commas, we have added the variable “$F”. After this, the “then” clause started with the “echo” statement using the variable name to show if it exists or not. The “then” part of the “if-then” statement will only be executed when the condition “if” will be true.

Let’s run the bash file using the “bash” keyword followed by the name of a file “direc.sh”. As the file exists in the home directory of our system, thus it executed the echo statement and is showing that the file exists. The output of the below-stated command is attached in the image.

The same thing can be achieved with the use of square brackets around the condition of the “if” clause without using the keyword “test” as shown below. Let’s execute it to see its result in the bash output screen within the shell.

After running this updated code, we have got the very same result i.e. file exists. The output of the below-stated command is attached in the image.

Example 02: Check If Directory Exists

Let’s take a look at the code that is used to check if the directory of the folder exists in our system or not. For that, we will be using a purely new folder. Therefore, within the terminal shell query area, we have tried the “mkdir” command to create a new directory named “new”. This newly created directory will be used within our code to check if it exists or not. The list command is executed to see all the existing directories and files in the home folder. We can see the “new” directory listed in the shown output beneath the “Music” folder and after the “Downloads”. The output of the below-stated command is attached in the image.

Читайте также:  Mp4 linux no sound

Let’s open up the same “direc.sh” file in Ubuntu’s nano editor to create a new code. After the file is launched, we need to create a new directory variable “D” holding a path to a newly created directory named “new” as “/home/Linux/new”. The overall work to check the directory existence has been done within the “if-then-else” statement of bash. So, the “if” statement has been started with the condition to check the directory in a system using the “-d” flag for “directory” along with the directory variable in inverted commas. This condition has been utilized within the square brackets. If the condition got satisfied and the directory exists, the “then” statement will be executed along with its “echo” statement. Otherwise, the “else” part of the statement will be utilized along with its “echo” statement showing that the file doesn’t exist. The overall statement will be closed by the “fi” keyword as shown below.

Now, it’s time to run our bash code in the terminal shell using the “bash” query shown in the image. After running it, we have got the success message showing that the directory exists. The output of the below-stated command is attached in the image.

If you want to achieve the else part execution in the shell terminal, you must have to delete the directory so that the condition doesn’t get satisfied. Therefore, we have deleted the newly made empty directory “new” from the home folder of our Ubuntu 20.04 system. After this, we have listed the contents of the home folder using the list command and found that there is no directory of the name “new” as below. After running the same “direc.sh” bash file with the “bash” instruction, we have got the output showing that the else part of the code has been executed i.e., directory doesn’t exist.

Conclusion

Finally! We have done the explanation of checking out if the directory exists in our Ubuntu 20.04 system or not. For this, we have tried the bash script to achieve our goal. We have also discussed the use of “-f” for file checking and “-d” for directory checking in the system. All the examples are simple and according to our user choice.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

How To Check If File or Directory Exists in Bash

Introductory image to check file or directory in Bash.

Note: You may encounter the term bash script. This is a sequence of several commands to the shell. A script can be saved as a file and is often used to automate multiple system commands into a single action.

How to Check if a File Exists

To test for the file /tmp/test.log, enter the following from the command line:

The first line executes the test to see if the file exists. The second command, echo, displays the results 0 meaning that the file exists, 1 means no file was found.

Читайте также:  Free unlimited vpn linux

In our example, the result was 1.

The result 1 indicates that no file was found ehan using echo command.

Now try creating a file, then testing for it:

As we have created the file beforehand, the result now is 0:

The result 0 indicates that the file is found.

You can also use square brackets instead of the test command:

How to Check if a Directory Exists

To check if a directory exists, switch out the –f option on the test command for –d (for directory):

Create that directory, and rerun the test:

This command works the same as it does for files, so using brackets instead of the test command works here also.

Note: If you are searching for a file or directory because you need to delete it, refer to our guide on removing files and directories with Linux command line.

How to Check if a File Does not Exist

Typically, testing for a file returns 0 (true) if the file exists, and 1 (false) if the file does not exist. For some operations, you may want to reverse the logic. It is helpful if you write a script to create a particular file only if it doesn’t already exist.

To create a file if one doesn’t already exist, enter the following at a command line:

[ ! –f /tmp/test.txt ] && touch /tmp/test.txt

The exclamation point ! stands for not. This command makes sure there is not a file named test.txt in the /tmp directory. You won’t see anything happen.

To see if the system created the file, enter the following:

You should see test.txt listed. You can use a similar command for a directory – replace the –f option with –d:

[ ! –d /tmp/test ] && touch /tmp/test 

How to Check for Multiple Files

To test for two files at the same time use the && option to add a second file:

[ -f /tmp/test.txt && -f /tmp/sample.txt ] && echo “Both files were found”

To test for multiple files with a wildcard, like an asterisk * to stand for various characters:

[ -f /tmp/*.jpg ] && echo “Files were found”

As usual, changing the –f option to –d lets you run the same test for multiple directories.

File Test Operators to Find Prticular Types of Files

Here are several commands to test to find specific types of files:

There are many other options available. Please consult the main page (test ––help) for additional options.

Working with Code Snippets

The previous commands work well for a simple two-line command at a command prompt. You can also use bash with multiple commands. When several commands are strung together, they are called a script.

A script is usually saved as a file and executed. Scripting also uses logical operators to test for a condition, then takes action based on the results of the test.

To create a script file, use the Nano editor to open a new file:

Enter one of the snippets from below, including the #!/bin/bash identifier. Use Ctrl-o to save the file, then Ctrl-x to exit Nano. Then, run the script by entering:

The following code snippet tests for the presence of a particular file. If the file exists, the script displays File exists on the screen.

#!/bin/bash if [ -f /tmp/test.txt ] then echo “File exists” fi

This works the same if you’re checking for a directory. Just replace the –f option with –d:

#!/bin/bash if [ -d /tmp/test ] then echo “File exists” fi

This command checks for the directory /tmp/test. If it exists, the system displays File exists.

You can now use bash to check if a file and directory exist. You can also create simple test scripts as you now understand the functions of a basic bash script file. Next, you should check out our post on Bash Function.

Читайте также:  Change user permission file linux

Источник

Check If Directory Exists In Linux With Bash

Check If Directory Exists In Linux With Bash

It’s useful to know how to check if a directory exists in linux from a bash script. A directory is a folder within a path in your linux system where all sorts of files and directories are stored. Your Music folder is a directory to store music files and your Downloads folder is a directory where all sorts files are downloaded from the web. You get the idea.

If Directory Exists

Lets start off with a simple example. You can copy all examples in this tutorial to a file and run the file yourself in a terminal to test for yourself. Check if a directory exists:

#!/bin/bash dload_dir=$HOME/Downloads if [ -d "$dload_dir" ]; then echo "$dload_dir exists" else echo "$dload_dir does not exist" fi
  • The “$dload_dir” variable value is the default Downloads directory in the system.
  • The “$HOME” linux built-in variable points to the path “/home/username/”.
  • Left square bracket “[” is a “test” command.
  • “-d” tells the test command to check if the file exists and if it’s a directory.

When you run the code above it will output the directory “exists” and “does not exist” if it doesn’t.

We will now do the opposite and check if the directory does not exist.

Check if a directory does not exists:

#!/bin/bash dload_dir=$HOME/Downloads if [ ! -d "$dload_dir" ]; then echo "$dload_dir does not exist" else echo "$dload_dir exists" fi

The sample above is nearly the same, but we add a “!” symbol and swap the two echo commands. The “!” symbol tells the test command to instead check if the directory does not exist.

Now that we’ve covered the basics to checking for a directory, lets get a little more advanced.

Check if a directory exists and if not, then create it:

#!/bin/bash dload_dir=$HOME/Downloads/myfolder if [ ! -d "$dload_dir" ]; then mkdir "$dload_dir" echo "$dload_dir was created." else echo "$dload_dir already exists" fi

In the code above we use the “mkdir” command to create a new directory.

If you run the code above it will create a directory named “myfolder” in the Downloads directory and let you know it was created. If you run the code a second time, it will say that it already exists.

Check if a directory is empty:

#!/bin/bash dload_dir=$HOME/Downloads if [ "$(ls -A $dload_dir)" ]; then echo "$dload_dir is not empty." else echo "$dload_dir is empty" fi

In the sample above we use the list “ls” command with the “-A” flag which tells ls to list all files and directories including the hidden ones in the Downloads directory. If files or directories are found, it lets you know the directory is not empty.

Pass any directory to a bash script:

#!/bin/bash my_dir=$1 if [ "$(ls -A $my_dir)" ]; then echo "$my_dir is not empty." else echo "$my_dir is empty" fi

Copy the code above to a file and name the file “file.sh” then give the file execute permissions.

Now to use the script you just created, you pass it the directory you wish to check. Like this:

If you noticed, the variable has changed to “$1”. This allows the script to take one argument which would be the directory you pass to it.

You can use this script to check if any directory is empty by simply passing the directory to the script as demonstrated.

Conclusion

This brings the tutorial to an end. This was a quick look at how to do checks on directories in linux with bash.

Источник

Оцените статью
Adblock
detector