Linux bash проверить существование файла

Bash: Test If File Exists

While creating a bash script, it is commonly helpful to test if file exists before attempting to perform some action with it.

This is a job for the test command, that allows to check if file exists and what type is it.

As only the check is done – the test command sets the exit code to 0 ( TRUE ) or 1 ( FALSE ), whenever the test succeeded or not.

Also the test command has a logical “not” operator which allows to get the TRUE answer when it needs to test if file does not exist.

Cool Tip: Create a clever bash script! Make it do more tests! Check easily whether a string exists in a file! Read more →

Bash Shell: Test If File Exists

Run one of the below commands to check whether a file exists:

Test if the file /etc/passwd exist ( TRUE ):

$ test -f /etc/passwd $ echo $? 0 $ [ -f /etc/passwd ] $ echo $? 0

Test if the file /etc/bebebe exist ( FALSE ):

$ test -f /etc/bebebe $ echo $? 1 $ [ -f /etc/bebebe ] $ echo $? 1

Test if the file /etc/bebebe does not exist ( TRUE ):

$ test ! -f /etc/bebebe $ echo $? 0 $ [ ! -f /etc/bebebe ] $ echo $? 0

If File Exists, Then …

We usually test if a file exists to perform some action depending on the result of the test.

Maybe if file doesn’t exist – there is no sens to move forward and it is required to break the script or whatever.

In the examples below, lets print corresponding messages depending on the results of the test command.

Cool Tip: The CASE statement is the simplest form of the IF-THEN-ELSE statement! If you have many ELIF elements – it is better to use the CASE ! Read more →

Test if the file /etc/passwd exists and print a message if it is TRUE :

$ if [ -f "/etc/passwd" ]; then echo "The file exists"; fi The file exists

Test if the file /etc/bebebe does not exist and print a message if it is TRUE :

$ if [ ! -f "/etc/bebebe" ]; then echo "The file does not exist"; fi The file does not exist

Test if the file exists and print a corresponding message in the each case:

$ [ -f "/etc/passwd" ] && echo "The file exists" || echo "The file does not exist" The file exists $ [ -f "/etc/bebebe" ] && echo "The file exists" || echo "The file does not exist" The file does not exist

Bash Script: Test If File Exists

Lets create a bash script, that will check whether a passed as an argument file exists or not, by printing a corresponding message.

Читайте также:  Linux can open file to write

Create an empty checkfile.sh file with the touch checkfile.sh command.

Make it executable with chmod +x checkfile.sh .

Open the checkfile.sh with a text editor and put the following code:

#!/bin/bash FILE=$1 if [ -f $FILE ]; then echo "The file '$FILE' exists." else echo "The file '$FILE' in not found." fi

Cool Tip: A good bash script prints usage and exits if arguments are not provided! It is very simple to configure! Read more →

Save and execute the script as follows:

$ ./checkfile.sh /etc/bebebe The file '/etc/bebebe' is not found. $ ./script.sh /etc/passwd The file '/etc/passwd' exists.

Test If File Exists And It Is …

In the examples above with the -f operator we only check whether a file exists and it is a regular file.

Here are some other useful options that can help to check whether a “file” exists and has specific permissions or it is a symbolic link, socket or a directory:

Option Description
-e Test if file exists, regardless of type (directory, socket, etc.)
-f Test if file exists and is a regular file
-r Test if file exists and read permission is granted
-w Test if file exists and write permission is granted
-x Test if file exists and execute permission is granted
-L Test if file exists and is a symbolic link
-S Test if file exists and is a socket
-d Test if directory exists

Run man test to see all available operators.

Источник

How To Check If File or Directory Exists in Bash

Introductory image to check file or directory 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.

The result 1 indicates that no file was found ehan using echo command.

Now try creating a file, then testing for it:

As we have created the file beforehand, the result now is 0:

The result 0 indicates that the file is found.

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.

Читайте также:  Astra linux virtualbox ошибка

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.

Источник

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

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

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

Читайте также:  System rescue cd usb linux

Проверка существования файла 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, а также его пустоты. Обе функции дополняют друг друга, поэтому использовать их в связке — эффективный приём.

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

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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