- Bash Check If Directory Exists
- Example 01: Check If File Exists
- Example 02: Check If Directory Exists
- Conclusion
- About the author
- Omar Farooq
- bash проверки существования файла, директории, пользователя
- Добавить комментарий Отменить ответ
- Теги
- Категории
- Похожие записи
- InqSoft Sign 0f Misery, автокликер для пожирания банок CP в Lineage II
- ProFtpd слушаем два сетевых интерфейса
- Будем предусмотрительны. Запрещаем автозапуск, запись и чтение USB-устройств.
- How To Check If File or Directory Exists in Bash
- How to Check if a File Exists
- How to Check if a Directory Exists
- How to Check if a File Does not Exist
- How to Check for Multiple Files
- File Test Operators to Find Prticular Types of Files
- Working with Code Snippets
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.
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.
bash проверки существования файла, директории, пользователя
Вот так будет самый точный поиск пользователя:
grep «^test1:» /etc/passwd
grep «test1:» /etc/passwd
test1:x:999:1003:Hi the test1:/home/test1:/bin/bash
test-test1:x:997:1003:Hi the test-test1:/home/test1:/bin/false
test1www:x:996:1003:Hi the test1www:/home/test1:/bin/false
[email protected]:~# grep «^test1:» /etc/passwd
test1:x:999:1003:Hi the test1:/home/test1:/bin/bash
Эм, а на практике проверял код?
Только что создал тестовый файлик с кодом
grep «test2» /etc/passwd >/dev/null
if [ $? -ne 0 ]; then
echo ‘No username found’
fi
проверяем:
[email protected]:~$ bash usr.sh
No username found
[email protected]:~$ sh usr.sh
No username found
Проверка существования пользователя не точная:
если существует пользователь, например, test2
А grep ищем несуществующего пользователя test, то его найдет.
Добавить комментарий Отменить ответ
Теги
Категории
Похожие записи
InqSoft Sign 0f Misery, автокликер для пожирания банок CP в Lineage II
Я все также иногда захожу пошпилить в линейку, на сервере l2.overworld.su, захожу просто пофанится, попвпешится, кстати играю на иксписят))) В…
ProFtpd слушаем два сетевых интерфейса
Недавно на один из фтп серверов поставил вторую сетевую карту и понадобилось забиндить ProFTPd на вторую сетевку, все проще чем…
Будем предусмотрительны. Запрещаем автозапуск, запись и чтение USB-устройств.
Случаются в нашей жизни ситуации, когда требуется ограничить доступ пользователя к USB-устройству, запретить его автозапуск, ограничить права на запись, а…
How To Check If File or Directory Exists 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.
In our example, the result was 1.
Now try creating a file, then testing for it:
As we have created the file beforehand, the result now is 0:
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.