Linux does file exist

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
Читайте также:  Acer predator helios 300 linux

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)

Источник

How to check if a file exists in a shell script

I’d like to write a shell script which checks if a certain file, archived_sensor_data.json , exists, and if so, deletes it. Following http://www.cyberciti.biz/tips/find-out-if-file-exists-with-conditional-expressions.html, I’ve tried the following:

However, this throws an error

when I try to run the resulting test_controller script using the ./test_controller command. What is wrong with the code?

6 Answers 6

You’re missing a required space between the bracket and -e :

Here is an alternative method using ls :

If you want to hide any output from ls so you only see yes or no, redirect stdout and stderr to /dev/null :

The backdrop to my solution recommendation is the story of a friend who, well into the second week of his first job, wiped half a build-server clean. So the basic task is to figure out if a file exists, and if so, let’s delete it. But there are a few treacherous rapids on this river:

Everything is a file.

Scripts have real power only if they solve general tasks

To be general, we use variables

We often use -f force in scripts to avoid manual intervention

And also love -r recursive to make sure we create, copy and destroy in a timely fashion.

Consider the following scenario:

We have the file we want to delete: filesexists.json

This filename is stored in a variable

We also hava a path variable to make things really flexible

So let’s see if -e does what it is supposed to. Does the files exist?

Читайте также:  Windows 10 максимальная 64 bit для установки с флешки

However, what would happen, if the file variable got accidentally be evaluated to nuffin’

What? It is supposed to return with an error. And this is the beginning of the story how that entire folder got deleted by accident

An alternative could be to test specifically for what we understand to be a ‘file’

So the file exists.

So this is not a file and maybe, we do not want to delete that entire directory

Источник

Проверка существования файла Bash

В операционных системах GNU/Linux любые объекты системы являются файлами. И проверка существования файла bash — наиболее мощный и широко применяемый инструмент для определения и сравнения в командном интерпретаторе.

В рамках интерпретатора Bash, как и в повседневном понимании людей, все объекты файловой системы являются, тем, чем они есть, каталогами, текстовыми документами и т.д. В этой статье будет рассмотрена проверка наличия файла Bash, а также его проверка на пустоту, и для этого используется команда test.

Проверка существования файла Bash

Начать стоит с простого и более общего метода. Параметр -e позволяет определить, существует ли указанный объект. Не имеет значения, является объект каталогом или файлом.

#!/bin/bash
# проверка существования каталога
if [ -e $HOME ]
then
echo «Каталог $HOME существует. Проверим наличие файла»
# проверка существования файла
if [ -e $HOME/testing ]
then
# если файл существует, добавить в него данные
echo «Строка для существующего файла» >> $HOME/testing
echo «Файл существует. В него дописаны данные.»
else
# иначе — создать файл и сделать в нем новую запись
echo «Файл не существует, поэтому создается.»
echo «Создание нового файла» > $HOME/testing
fi
else
echo «Простите, но у вас нет Домашнего каталога»
fi

Пример работы кода:

Вначале команда test проверяет параметром -e, существует ли Домашний каталог пользователя, название которого хранится системой в переменной $HOME. При отрицательном результате скрипт завершит работу с выводом сообщения об этом. Если такой каталог обнаружен, параметр продолжает проверку. На этот раз ищет в $HOME файл testing. И если он есть, то в него дописывается информация, иначе он создастся, и в него запишется новая строка данных.

Проверка наличия файла

Проверка файла Bash на то, является ли данный объект файлом (то есть существует ли файл), выполняется с помощью параметра -f.

#!/bin/bash
if [ -f $HOME ]
then
echo «$HOME — это файл»
else
echo «$HOME — это не файл»
if [ -f $HOME/.bash_history ]
then
echo «А вот .bash_history — файл»
fi
fi

Пример работы кода:

В сценарии проверяется, является ли $HOME файлом. Результат проверки отрицательный, после чего проверяется настоящий файл .bash_history, что уже возвращает истину.

На заметку: на практике предпочтительнее использовать сначала проверку на наличие объекта как такового, а затем — на его конкретный тип. Так можно избежать различных ошибок или неожиданных результатов работы программы.

Проверка файла на пустоту

Чтобы определить, является ли файл пустым, нужно выполнить проверку с помощью параметра -s. Это особенно важно, когда файл намечен на удаление. Здесь нужно быть очень внимательным к результатам, так как успешное выполнение этого параметра указывает на наличие данных.

#!/bin/bash
file=t15test
touch $file
if [ -s $file ]
then
echo «Файл $file содержит данные.»
else
echo «Файл $file пустой.»
fi
echo «Запись данных в $file. »
date > $file
if [ -s $file ]
then
echo «Файл $file содержит данные.»
else
echo «Файл $file все еще пустой.»
fi

Результат работы программы:

В этом скрипте файл создаётся командой touch, и при первой проверке на пустоту возвращается отрицательный результат. Затем в него записываются данные в виде команды date, после чего повторная проверка файла возвращает истину.

Выводы

В статье была рассмотрена проверка существования файла bash, а также его пустоты. Обе функции дополняют друг друга, поэтому использовать их в связке — эффективный приём.

Хороший тон в написании сценариев командного интерпретатора — сначала определить тип файла и его дальнейшую роль в программе, а затем уже проверять объект на существование.

Источник

How do I tell if a regular file does not exist in Bash?

I’ve used the following script to see if a file exists:

What’s the correct syntax to use if I only want to check if the file does not exist?

20 Answers 20

The test command ( [ here) has a «not» logical operator which is the exclamation point (similar to many other languages). Try this:

Bash File Testing

-b filename — Block special file
-c filename — Special character file
-d directoryname — Check for directory Existence
-e filename — Check for file existence, regardless of type (node, directory, socket, etc.)
-f filename — Check for regular file existence not a directory
-G filename — Check if file exists and is owned by effective group ID
-G filename set-group-id — True if file exists and is set-group-id
-k filename — Sticky bit
-L filename — Symbolic link
-O filename — True if file exists and is owned by the effective user id
-r filename — Check if file is a readable
-S filename — Check if file is socket
-s filename — Check if file is nonzero size
-u filename — Check if file set-user-id bit is set
-w filename — Check if file is writable
-x filename — Check if file is executable

Читайте также:  Windows 10 форматировать флешку fat16

How to use:

A test expression can be negated by using the ! operator

You can negate an expression with «!»:

The relevant man page is man test or, equivalently, man [ — or help test or help [ for the built-in bash command.

Also, it’s possible that the file is a broken symbolic link, or a non-regular file, like e.g. a socket, device or fifo. For example, to add a check for broken symlinks:

It’s worth mentioning that if you need to execute a single command you can abbreviate

I prefer to do the following one-liner, in POSIX shell compatible format:

For a couple of commands, like I would do in a script:

Once I started doing this, I rarely use the fully typed syntax anymore!!

To test file existence, the parameter can be any one of the following:

All the tests below apply to regular files, directories, and symlinks:

You can do this:

If you want to check for file and folder both, then use -e option instead of -f . -e returns true for regular files, directories, socket, character special files, block special files etc.

You should be careful about running test for an unquoted variable, because it might produce unexpected results:

The recommendation is usually to have the tested variable surrounded by double quotation marks:

the [ command does a stat() (not lstat() ) system call on the path stored in $file and returns true if that system call succeeds and the type of the file as returned by stat() is «regular«.

So if [ -f «$file» ] returns true, you can tell the file does exist and is a regular file or a symlink eventually resolving to a regular file (or at least it was at the time of the stat() ).

However if it returns false (or if [ ! -f «$file» ] or ! [ -f «$file» ] return true), there are many different possibilities:

  • the file doesn’t exist
  • the file exists but is not a regular file (could be a device, fifo, directory, socket. )
  • the file exists but you don’t have search permission to the parent directory
  • the file exists but that path to access it is too long
  • the file is a symlink to a regular file, but you don’t have search permission to some of the directories involved in the resolution of the symlink.
  • . any other reason why the stat() system call may fail.

In short, it should be:

To know for sure that the file doesn’t exist, we’d need the stat() system call to return with an error code of ENOENT ( ENOTDIR tells us one of the path components is not a directory is another case where we can tell the file doesn’t exist by that path). Unfortunately the [ command doesn’t let us know that. It will return false whether the error code is ENOENT, EACCESS (permission denied), ENAMETOOLONG or anything else.

The [ -e «$file» ] test can also be done with ls -Ld — «$file» > /dev/null . In that case, ls will tell you why the stat() failed, though the information can’t easily be used programmatically:

At least ls tells me it’s not because the file doesn’t exist that it fails. It’s because it can’t tell whether the file exists or not. The [ command just ignored the problem.

With the zsh shell, you can query the error code with the $ERRNO special variable after the failing [ command, and decode that number using the $errnos special array in the zsh/system module:

Источник

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