- Как проверить, существует ли файл или каталог в Bash
- Проверьте, существует ли файл
- Проверить, существует ли каталог
- Проверьте, не существует ли файла
- Проверьте, существует ли несколько файлов
- Операторы проверки файлов
- Выводы
- Bash Shell: Check File Exists or Not
- File test operators
- Single command to check if file exists, and print (custom) message to stdout?
- Checking if a file exists in several directories
- 7 Answers 7
- How to check if a directory exists in Linux command line?
- 7 Answers 7
- Related
- Hot Network Questions
- Subscribe to RSS
Как проверить, существует ли файл или каталог в Bash
Часто при написании сценариев оболочки вы можете оказаться в ситуации, когда вам нужно выполнить действие в зависимости от того, существует файл или нет.
В Bash вы можете использовать команду test, чтобы проверить, существует ли файл, и определить тип файла.
Команда test принимает одну из следующих синтаксических форм:
Если вы хотите, чтобы ваш сценарий был переносимым, вам следует предпочесть старую команду test [ , которая доступна во всех оболочках POSIX. Новая обновленная версия тестовой команды [[ (двойные скобки) поддерживается в большинстве современных систем, использующих Bash, Zsh и Ksh в качестве оболочки по умолчанию.
Проверьте, существует ли файл
При проверке существования файла наиболее часто используются операторы FILE -e и -f . Первый проверит, существует ли файл независимо от типа, а второй вернет истину, только если ФАЙЛ является обычным файлом (а не каталогом или устройством).
Наиболее удобочитаемый вариант при проверке существования файла — использование команды test в сочетании с оператором if . Любой из приведенных ниже фрагментов проверит, существует ли файл /etc/resolv.conf :
Если вы хотите выполнить другое действие в зависимости от того, существует файл или нет, просто используйте конструкцию if / then:
Вы также можете использовать команду test без оператора if. Команда после оператора && будет выполнена только в том случае, если статус выхода тестовой команды — истина,
Если вы хотите запустить серию команд после оператора && просто заключите команды в фигурные скобки, разделенные ; или && :
Напротив && , оператор после || Оператор будет выполняться только в том случае, если статус выхода тестовой команды false .
Проверить, существует ли каталог
Операторы -d позволяют вам проверить, является ли файл каталогом или нет.
Например, чтобы проверить, существует ли каталог /etc/docker вы должны использовать:
Вы также можете использовать двойные скобки [[ вместо одинарной [ .
Проверьте, не существует ли файла
Как и во многих других языках, тестовое выражение может быть отменено с помощью ! (восклицательный знак) оператор логического НЕ:
То же, что и выше:
Проверьте, существует ли несколько файлов
Вместо использования сложных вложенных конструкций if / else вы можете использовать -a (или && с [[ ), чтобы проверить, существует ли несколько файлов:
Эквивалентные варианты без использования оператора IF:
Операторы проверки файлов
Команда test включает в себя следующие операторы FILE, которые позволяют проверять файлы определенных типов:
- -b FILE — Истина, если ФАЙЛ существует и является специальным блочным файлом.
- -c FILE — Истина, если ФАЙЛ существует и является файлом специальных символов.
- -d FILE — Истина, если ФАЙЛ существует и является каталогом.
- -e FILE — Истина, если ФАЙЛ существует и является файлом, независимо от типа (узел, каталог, сокет и т. д.).
- -f FILE — Истина, если ФАЙЛ существует и является обычным файлом (не каталогом или устройством).
- -G FILE — Истина, если ФАЙЛ существует и имеет ту же группу, что и пользователь, выполняющий команду.
- -h FILE — Истина, если ФАЙЛ существует и является символической ссылкой.
- -g FILE — Истина, если ФАЙЛ существует и для него установлен флаг set-group-id ( sgid ).
- -k FILE — Истина, если ФАЙЛ существует и для него установлен флаг липкого бита.
- -L FILE — Истина, если ФАЙЛ существует и является символической ссылкой.
- -O FILE — Истина, если ФАЙЛ существует и принадлежит пользователю, выполняющему команду.
- -p FILE — Истина, если ФАЙЛ существует и является каналом.
- -r FILE — Истинно, если ФАЙЛ существует и доступен для чтения.
- -S FILE — Истина, если ФАЙЛ существует и является сокетом.
- -s FILE — Истина, если ФАЙЛ существует и имеет ненулевой размер.
- -u FILE — Истинно, если ФАЙЛ существует и установлен флаг set-user-id ( suid ).
- -w FILE — Истина, если ФАЙЛ существует и доступен для записи.
- -x FILE — Истина, если ФАЙЛ существует и является исполняемым.
Выводы
В этом руководстве мы показали вам, как проверить, существует ли файл или каталог в Bash.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Источник
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.
Источник
Single command to check if file exists, and print (custom) message to stdout?
Hope it’s OK to note this, now that I’ve encountered it:
I’m already aware that one can test for file existence using the test ( [ ) command:
. but that’s a bit of typing there 🙂 So, I was wandering if there is a «default» single command, that will return the file existence result to stdout ?
I can also use test with the exit status $? :
. but this is still two commands — and the logic is also «inverse» (0 for success, and nonzero for failure).
The reason I’m asking is that I need to test for file existence in gnuplot , whose » system(«command») returns the resulting character stream from stdout as a string.«; in gnuplot I can do directly:
so I’d basically like to be able to write something like this (pseudo):
. unfortunately, I cannot use that directly via test and $? :
. I’d have to invert the logic.
So, I’d basically have to come up with sort of a custom script solution (or writing a script inline as one-liner) . and I thought, if there is already a default command that can print 0 or 1 (or a custom message) to stdout for file existence, then I don’t have to do so 🙂
(note that ls may be a candidate, but it’s stdout output is far too verbose; and if I want to avoid that, I’d have to suppress all output and again return exist status, as in
. but that’s again two commands (and more typing), and «inverted» logic. )
So, is there a single default command that can do this in Linux?
Источник
Checking if a file exists in several directories
I need a script that will look at files in a directory and see if it exists in one of several directories.
I need something like this:
the files will not be in the root of the directory. I can’t just search /media, because I don’t want to search in cd-rom or videos.
I am using the latest version of Ubuntu server.
7 Answers 7
You don’t mention if you need to keep the files (perhaps removing duplicates?), hardlink them or anything else.
So, depending on your intention, the best solution would be to use one program like rdfind (not interactive), fdupes (more interactive, allowing you to choose which files to keep or not), duff (to only report the files that were duplicate) or many others.
If you want something fancier with a GUI that will let you choose what to keep via a point-and-click interface, then fslint (via its fslint-gui command) would be my recommended choice.
All of the above are available in Debian’s repository and, by transition, I think that they are in Ubuntu’s or Linux Mint’s repositories, if that’s what you are using.
This could be very slow if you traverse /downloads or /media for each file name. So traverse each hierarchy only once, store the list of file names, and then process the lists.
For simplicity, I assume that your file names don’t contain any newlines.
At this point, the two .find files contain lists of file paths, with the name of the file prepended, sorted by file name. Join the files on the first / -separated field, and clean up the result a bit.
Here is an implementation in bash using brace expansion:
This will list all files in downloads that are also in your specified /media subdirectories:
and this will just print whether the file has been found in one of those /media sub-directories or not.
If there are many files in /downloads, running find once for each file will be very slow. That can be solved (if you are using GNU find ) by building a regular expression containing all the filenames you want to search for and using GNU find ‘s -regex or -iregex options.
And here’s another version that doesn’t use the shell built-in read so should be much faster:
Both of these regexp versions are limited by the maximum line length of a shell command — too many files and they will fail.
NOTE: like most other answers here, these examples do not cope with filenames that have newlines ( \n ) in them. Any other character, including space, is fine.
Источник
How to check if a directory exists in Linux command line?
How to check if a directory exists in Linux command line?
Solution: [ -d ¨a¨ ]&&echo ¨exists¨||echo ¨not exists¨
7 Answers 7
Assuming your shell is BASH:
The canonical way is to use the test(1) utility:
where path is the pathname of the directory you want to check for.
For example:
[ -d «YOUR_DIR» ] && echo «is a dir»
[ -d / ] && echo «root dir «
will output: root dir .
To check if a directory exists in a shell script you can use the following:
to check the opposite , add ! before the -d ->[ ! -d . ]
I usually just ls it:
If it exists, you’ll see its contents, if it doesn’t exist you’ll see an error like this:
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник