- Как проверить, существует ли файл или каталог в Bash
- How to Check if a File or Directory Exists in Bash
- В Bash вы можете использовать тестовую команду, чтобы проверить, существует ли файл и определить тип файла.
- Проверьте, существует ли файл
- Проверьте, существует ли каталог
- Проверьте, не существует ли файл
- Проверьте, существует ли несколько файлов
- Операторы проверки файлов
- Вывод
- Linux / UNIX: Find Out If File Exists With Conditional Expressions in a Bash Shell
- Syntax to find out if file exists with conditional expressions in a Bash Shell
- Find out if file /etc/passwd file exist or not
- How can I tell if a regular file named /etc/foo does not exist in Bash?
- [[ example
- Find out if directory /var/logs exist or not
- [[ example
- Are two files are the same?
- How to check if a file exists in a shell script
- A complete list for file testing in bash shell
- Conclusion
- Bash Shell: Check File Exists or Not
- File test operators
Как проверить, существует ли файл или каталог в Bash
How to Check if a File or Directory Exists in Bash
В Bash вы можете использовать тестовую команду, чтобы проверить, существует ли файл и определить тип файла.
Во многих случаях при написании сценариев Shell вы можете оказаться в ситуации, когда вам нужно выполнить действие, основанное на том, существует файл или нет.
Команда test принимает одну из следующих синтаксических форм:
Если вы хотите, чтобы ваш скрипт был переносимым, вам следует использовать старую [ команду test , которая доступна во всех оболочках POSIX. Новая обновленная версия команды test [[ (двойные скобки) поддерживается в большинстве современных систем, использующих Bash, Zsh и Ksh в качестве оболочки по умолчанию.
Проверьте, существует ли файл
При проверке существования файла чаще всего используются операторы FILE -e и -f . Первый проверит, существует ли файл независимо от его типа, а второй вернет истину, только если ФАЙЛ является обычным файлом (не каталогом или устройством).
Наиболее читаемым вариантом при проверке существования файла является использование test команды в сочетании с if оператором . Любой из фрагментов ниже проверит, /etc/resolv.conf существует ли файл:
Вы также можете использовать команду test без оператора if. Команда после && оператора будет выполнена только в том случае, если статус выхода тестовой команды равен true,
Напротив && , оператор после || оператора будет выполняться только в том случае, если статус выхода команды test равен false .
Проверьте, существует ли каталог
Операторы -d позволяют проверить, является ли файл каталогом или нет.
Например, чтобы проверить, /etc/docker существует ли каталог, вы должны использовать:
Вы также можете использовать двойные скобки [[ вместо одной [ .
Проверьте, не существует ли файл
Как и во многих других языках, тестовое выражение можно отменить, используя ! логический оператор not (восклицательный знак):
То же, что и выше:
Проверьте, существует ли несколько файлов
Вместо использования сложных вложенных конструкций if / else вы можете использовать -a (или && с [[ ), чтобы проверить, существует ли несколько файлов:
Операторы проверки файлов
Команда test включает в себя следующие операторы FILE, которые позволяют вам тестировать определенные типы файлов:
- -b FILE — Истина, если ФАЙЛ существует и является специальным файлом блока.
- -c FILE — Истина, если ФАЙЛ существует и является файлом специальных символов.
- -d FILE — Истина, если ФАЙЛ существует и является каталогом.
- -e FILE — Истина, если ФАЙЛ существует и является файлом, независимо от его типа (узел, каталог, сокет и т. Д.).
- -f FILE — Истина, если ФАЙЛ существует и является обычным файлом (не каталогом или устройством).
- -G FILE — Истина, если ФАЙЛ существует и имеет ту же группу, что и пользователь, выполняющий команду.
- -h FILE — Истина, если ФАЙЛ существует и является символической ссылкой.
- -g FILE — Истина, если ФАЙЛ существует и установлен sgid флаг set -group-id ( ).
- -k FILE — Истина, если ФАЙЛ существует и установлен флаг закрепления битов.
- -L FILE — Истина, если ФАЙЛ существует и является символической ссылкой.
- -O FILE — Истина, если ФАЙЛ существует и принадлежит пользователю, выполняющему команду.
- -p FILE — Истина, если ФАЙЛ существует и является каналом.
- -r FILE — Истина, если ФАЙЛ существует и доступен для чтения.
- -S FILE — Истина, если ФАЙЛ существует и является сокетом.
- -s FILE — Истина, если ФАЙЛ существует и имеет ненулевой размер.
- -u FILE — Истина, если ФАЙЛ существует и установлен suid флаг set-user-id ( ).
- -w FILE — Истина, если ФАЙЛ существует и доступен для записи.
- -x FILE — Истина, если ФАЙЛ существует и является исполняемым.
Вывод
В этом руководстве мы показали, как проверить, существует ли файл или каталог в Bash.
Источник
Linux / UNIX: Find Out If File Exists With Conditional Expressions in a Bash Shell
W ith the help of BASH shell and IF command, it is possible to find out if a file exists or not on the filesystem. A conditional expression (also know as “evaluating expressions”) can be used by [[ compound command and the test ( [ ) builtin commands to test file attributes and perform string and arithmetic comparisons.
You can easily find out if a regular file does or does not exist in Bash shell under macOS, Linux, FreeBSD, and Unix-like operating system. You can use [ expression ] , [[ expression ]] , test expression , or if [ expression ]; then . fi in bash shell along with a ! operator. Let us see various ways to find out if a file exists or not in bash shell.
Syntax to find out if file exists with conditional expressions in a Bash Shell
The general syntax is as follows:
[ parameter FILE ]
OR
test parameter FILE
OR
[[ parameter FILE ]]
Where parameter can be any one of the following:
- -e : Returns true value if file exists.
- -f : Return true value if file exists and regular file.
- -r : Return true value if file exists and is readable.
- -w : Return true value if file exists and is writable.
- -x : Return true value if file exists and is executable.
- -d : Return true value if exists and is a directory.
Please note that the [[ works only in Bash, Zsh and the Korn shell, and is more powerful; [ and test are available in POSIX shells. Let us see some examples.
Find out if file /etc/passwd file exist or not
Type the following commands:
$ [ -f /etc/passwd ] && echo «File exist» || echo «File does not exist»
$ [ -f /tmp/fileonetwo ] && echo «File exist» || echo «File does not exist»
How can I tell if a regular file named /etc/foo does not exist in Bash?
You can use ! operator as follows:
[ ! -f /etc/foo ] && echo «File does not exist» Exists
OR
[[ example
Enter the following commands at the shell prompt:
$ [[ -f /etc/passwd ]] && echo «File exist» || echo «File does not exist»
$ [[ -f /tmp/fileonetwo ]] && echo «File exist» || echo «File does not exist»
Find out if directory /var/logs exist or not
Type the following commands:
$ [ -d /var/logs ] && echo «Directory exist» || echo «Directory does not exist»
$ [ -d /dumper/fack ] && echo «Directory exist» || echo «Directory does not exist»
[[ example
$ [[ -d /var/logs ]] && echo «Directory exist» || echo «Directory does not exist»
$ [[ -d /dumper/fake ]] && echo «Directory exist» || echo «Directory does not exist»
Are two files are the same?
Use the -ef primitive with the [[ new test command:
How to check if a file exists in a shell script
You can use conditional expressions in a shell script:
Save and execute the script:
$ chmod +x script.sh
$ ./script.sh /path/to/file
$ ./script.sh /etc/resolv.conf
To check if a file exists in a shell script regardless of type, use the -e option:
You can use this technique to verify that backup directory or backup source directory exits or not in shell scripts. See example script for more information.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
A complete list for file testing in bash shell
From the test command man page:
[ Expression ] | Meaning |
---|---|
-b filename | Return true if filename is a block special file. |
-c filename | Return true if filename exists and is a character special file. |
-d filename | Return true filename exists and is a directory. |
-e filename | Return true filename exists (regardless of type). |
-f filename | Return true filename exists and is a regular file. |
-g filename | Return true filename exists and its set group ID flag is set. |
-h filename | Return true filename exists and is a symbolic link. This operator is retained for compatibility with previous versions of this program. Do not rely on its existence; use -L instead. |
-k filename | Return true filename exists and its sticky bit is set. |
-n filename | Return true the length of string is nonzero. |
-p filename | Return true filename is a named pipe (FIFO). |
-r filename | Return truefilename exists and is readable. |
-s filename | Return true filename exists and has a size greater than zero. |
-t file_descriptor | Return true the filename whose file descriptor number is file_descriptor is open and is associated with a terminal. |
-u filename | Return true filename exists and its set user ID flag is set. |
-w filename | Return true filename exists and is writable. True indicates only that the write flag is on. The file is not writable on a read-only file system even if this test indicates true. |
-x filename | Return true filename exists and is executable. True indicates only that the execute flag is on. If file is a directory, true indicates that file can be searched. |
-z string | Return true the length of string is zero. |
-L filename | Return true filename exists and is a symbolic link. |
-O filename | Return true filename exists and its owner matches the effective user id of this process. |
-G filename | Return true filename exists and its group matches the effective group id of this process. |
-S filename | Return true filename exists and is a socket. |
file1 -nt file2 | True if file1 exists and is newer than file2. |
file1 -ot file2 | True if file1 exists and is older than file2. |
file1 -ef file2 | True if file1 and file2 exist and refer to the same file. |
Conclusion
You just learned how to find out if file exists with conditional expressions in a Bash shell. For more information type the following command at shell prompt or see test command in our wiki or see bash man page here:
test(1)
Источник
Bash Shell: Check File Exists or Not
H ow do I test existence of a text file in bash running under Unix like operating systems?
You need to use the test command to check file types and compare values. The same command can be used to see if a file exist of not. The syntax is as follows:
The following command will tell if a text file called /etc/hosts exists or not using bash conditional execution :
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
The same code can be converted to use with if..else..fi which allows to make choice based on the success or failure of a test command:
File test operators
The following operators returns true if file exists:
(Fig.01: File test operators taken from bash man page)
The syntax is same (see File operators (attributes) comparisons for more info):
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
Thank you for the trick!
thanks much for that useful information
i made a linux script which receives as first argument a path to a directory. I don’t know the path. And i want to check if “file.txt” exists at that certain path . For example :
if [ -e $1/file.txt ];then echo HAHA fi
if you use -f with *.sock files it always says “the file does not exist”. when I use -e it worked 🙂
What if I want to test for the existence of any files with a particular filename extension? Is there a simple way to do that? I’ve trying to use the return status of the ls command but I seem to be getting the syntax a bit wrong.
You can use wildcard. Ex:
[ -e *”.extension” ]
(don’t forget to have a space character before the operator and before the closing branch, it took hours of my time to recognize this 😐 )
Can I mix the operator?
like:
if [-xw filename]
(Checking the existence of the file that executable and writable)
i want to write script to copy a some of the files inside directory to specified location(for example i have one directory, this containes 1000 image file. then i need pick only 100 image file from 1000 image file. also i have a list of images which i need to copy (i made one file).
can anyone help on this(please forword to my mail)
in my script I have[ $FILE ! = “”] ..what does it mean…
FILE has lot ma y rows extracted file names from database.
Источник