Test if directory exists linux

⛱ Проверьте, существует ли каталог в оболочке Linux или Unix

Скрипты

Нужно проверить, существует ли каталог в скрипте оболочки, работающем в Linux или Unix-подобной системе?

Как проверить, существует ли каталог в скрипте оболочки?

Каталог – это не что иное, как место для хранения файлов в системе Linux в иерархическом формате.

Например, $HOME/Downloads/ будет хранить все загруженные файлы или /tmp/ будет хранить временные файлы.

В этой статье показано, как узнать, существует ли каталог в Linux или Unix-подобных системах.

Как проверить, существует ли каталог в Linux

Можно проверить, существует ли каталог в скрипте оболочки Linux, используя следующий синтаксис:

Вы можете использовать ! чтобы проверить, существует ли каталог в Unix:

Можно проверить, существует ли каталог в скрипте Linux следующим образом:

DIR="/etc/httpd/" if [ -d "$DIR" ]; then # Take action if $DIR exists. # echo "Installing config files in $. " fi
DIR="/etc/httpd/" if [ -d "$DIR" ]; then ### Take action if $DIR exists ### echo "Installing config files in $. " else ### Control will jump here if $DIR does NOT exists ### echo "Error: $ not found. Can not continue." exit 1 fi

Linux проверяет, существует ли каталог, и предпринимает какие-то действия

Вот пример скрипта оболочки, чтобы увидеть, существует ли папка в Linux:

#!/bin/bash d="$1"   [ "$d" == "" ] && < echo "Usage: $0 directory"; exit 1; >[ -d "$" ] && echo "Directory $d found." || echo "Directory $d not found."

Запустите его следующим образом:

./test.sh
./test.sh /tmp/
./test.sh /itsecforu

Проверьте, существует ли каталог в bash, и если нет, то создайте его.

Вот пример скрипта оболочки, чтобы проверить, не существует ли каталог, и создать его в соответствии с нашими потребностями:

#!/bin/bash dldir="$HOME/linux/5.x" _out="/tmp/out.$$" # Build urls url="some_url/file.tar.gz" file="$" ### Check for dir, if not found create it using the mkdir ## [ ! -d "$dldir" ] && mkdir -p "$dldir" # Now download it wget -qc "$url" -O "$/$" # Do something else below #

Убедитесь, что вы всегда заключаете переменные оболочки, такие как $DIR, в двойные кавычки («$DIR», чтобы избежать неожиданностей в ваших скриптах:

DIR="foo" [ -d "$DIR" ] && echo "Found" ## ## this will fail as DIR will only expand to "foo" and not to "foo bar stuff" ## hence wrap it ## DIR="foo bar stuff" [ -d $DIR ] && echo "Found"

Использование команды test

Команду test можно использовать для проверки типов файлов и сравнения значений.

Например, посмотрите, существует ли FILE и является ли он каталогом. Синтаксис:

test -d "DIRECTORY" && echo "Found/Exists" || echo "Does not exist"

Команда test аналогична [условному выражению. Следовательно, вы также можете использовать следующий синтаксис:

[ -d «DIR» ] && echo «yes» || echo «noop»

Помощь

man bash help [ help [[ man test

Заключение

В этой статье описаны различные команды, которые можно использовать для проверки существования каталога в скриптов оболочки, работающем в Linux или Unix-подобных системах.

Читайте также:  Linux или windows переустановка

Пожалуйста, не спамьте и никого не оскорбляйте. Это поле для комментариев, а не спамбокс. Рекламные ссылки не индексируются!

Админ, спасай, выручай! В общем, в /mnt надо создать каталоги. Кусок скрипта: #!/bin/bash if[ ! -d “/mnt/1” -a ! -d “/mnt/2” -a ! -d “/mnt/4” -a ! -d “/mnt/5” -a ! -d “/mnt/6” -a ! -d “/mnt/7” -a ! -d “/mnt/8” -a ! -d “/mnt/9” -a ! -d “/mnt/10” -a ! -d “/mnt/11” ] ; then
sudo mkdir /mnt/
sudo chmod 777 -R
mnt/ ;
fi идет ругань на синтаксическую ошибку “then” если убрать ; то идет ругань на “fi”
проблема в ;. В примерах ее нужно писать. Подскажи как правильно написать скрипт, всю голову сломал.
Идет проверка, что этих каталогов не существует и он их создает и дает права. Спасибо

  • Аудит ИБ (49)
  • Вакансии (12)
  • Закрытие уязвимостей (105)
  • Книги (27)
  • Мануал (2 305)
  • Медиа (66)
  • Мероприятия (39)
  • Мошенники (23)
  • Обзоры (819)
  • Обход запретов (34)
  • Опросы (3)
  • Скрипты (114)
  • Статьи (352)
  • Философия (114)
  • Юмор (18)

Anything in here will be replaced on browsers that support the canvas element

В этой заметке вы узнаете о блокировке IP-адресов в Nginx. Это позволяет контролировать доступ к серверу. Nginx является одним из лучших веб-сервисов на сегодняшний день. Скорость обработки запросов делает его очень популярным среди системных администраторов. Кроме того, он обладает завидной гибкостью, что позволяет использовать его во многих ситуациях. Наступает момент, когда необходимо ограничить доступ к […]

Знаете ли вы, что выполняется в ваших контейнерах? Проведите аудит своих образов, чтобы исключить пакеты, которые делают вас уязвимыми для эксплуатации Насколько хорошо вы знаете базовые образы контейнеров, в которых работают ваши службы и инструменты? Этот вопрос часто игнорируется, поскольку мы очень доверяем им. Однако для обеспечения безопасности рабочих нагрузок и базовой инфраструктуры необходимо ответить […]

Одной из важнейших задач администратора является обеспечение обновления системы и всех доступных пакетов до последних версий. Даже после добавления нод в кластер Kubernetes нам все равно необходимо управлять обновлениями. В большинстве случаев после получения обновлений (например, обновлений ядра, системного обслуживания или аппаратных изменений) необходимо перезагрузить хост, чтобы изменения были применены. Для Kubernetes это может быть […]

Является ли запуск сервера NFS в кластере Kubernetes хорошей идеей или это ворота для хакеров Одним из многочисленных преимуществ сетевой файловой системы является ее способность выполнять многократное чтение-запись. И как и все в наши дни, NFS – это просто еще одна служба, которую можно запустить в своем кластере Kubernetes. Однако является ли сервер NFS подходящей […]

Репозитории Git хранят ценный исходный код и используются для создания приложений, работающих с конфиденциальными данными. Если злоумышленнику удастся скомпрометировать учетную запись GitHub с уязвимым репозиторием, он сможет перенести вредоносные коммиты прямо на производство. Подписанные коммиты помогают избежать этого. Что такое подписанные коммиты? Подписанные коммиты подразумевают добавление цифровой подписи к вашим коммитам с использованием закрытого криптографического […]

Источник

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.

Читайте также:  Kali linux vpn server

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.

Источник

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