Linux if any file exists

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:

[-e archived_sensor_data.json] && rm archived_sensor_data.json 

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

You must set one or more whitespace between opening square bracket «[» and option «-e» same as between filename and closing square bracket «]»

7 Answers 7

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

#!/bin/bash if [ -e x.txt ] then echo "ok" else echo "nok" fi 

I finally added two blank spaces, one after the opening square bracket and one before the closing one: [ -e archived_sensor_data.json ] && rm archived_sensor_data.json . The script seems to work now.

The main difference here is the fact that you are using «bash» scripting instead of «shell» scripting. Notice that the first line that you have added was #!/bin/bash, so you are telling the machine to use «bash» instead of sh. Because sh doesn’t recognize that argument «-e»

Here is an alternative method using ls :

(ls x.txt && echo yes) || echo no 

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

(ls x.txt >> /dev/null 2>&1 && echo yes) || echo no 

This code means: «if ls is successful, there is such file, otherwise, there is none». If ls failed, it does not mean that file is missing. It might be some other error. For example, create file in directory owned by root and try to do ls under regular user. It will fail with Permission denied , which is not equivalent that file does not exist.

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.
Читайте также:  Suse certified linux engineer

Consider the following scenario:

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

This filename is stored in a variable

:~/Documents/thisfolderexists filevariable="filesexists.json" 

We also hava a path variable to make things really flexible

:~/Documents/thisfolderexists pathtofile=".." :~/Documents/thisfolderexists ls $pathtofile filesexists.json history20170728 SE-Data-API.pem thisfolderexists 

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

:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $? 0 

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

:~/Documents/thisfolderexists filevariable="" :~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $? 0 

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’

:~/Documents/thisfolderexists filevariable="filesexists.json" :~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $? 0 
:~/Documents/thisfolderexists filevariable="" :~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $? 1 

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

man test has the following to say:

-b FILE FILE exists and is block special -c FILE FILE exists and is character special -d FILE FILE exists and is a directory -e FILE FILE exists -f FILE FILE exists and is a regular file . -h FILE FILE exists and is a symbolic link (same as -L) 

Источник

How can I check a file exists and execute a command if not?

I have a daemon I have written using Python. When it is running, it has a PID file located at /tmp/filename.pid . If the daemon isn’t running then PID file doesn’t exist. On Linux, how can I check to ensure that the PID file exists and if not, execute a command to restart it? The command would be

The «which has to be executed from a specific directory» part of your description sounds like a recipe for trouble. Beware — rethink if at all possible.

/tmp is a bad location to put PID files, since some distributions have cleaner processes that delete files from /tmp, and users may delete files from there to make space.

7 Answers 7

[ -f /tmp/filename.pid ] || python daemon.py restart 

-f checks if the given path exists and is a regular file (just -e checks if the path exists)

the [] perform the test and returns 0 on success, 1 otherwise

the || is a C-like or , so if the command on the left fails, execute the command on the right.

Читайте также:  Иерархия прав доступа linux

So the final statement says, if /tmp/filename.pid does NOT exist then start the daemon.

@Barakuda — A non-regular file could be a directory, named pipe, network socket, character device, symbolic link.

I think && is if the condition is met, while || is if it’s not met. [ -f my_file ] || echo ‘absent’ && echo ‘exists’

test -f filename && daemon.py restart || echo "File doesn't exists" 

if only the file needs to be checked for existence : test -f filename && echo «exists» || echo «does not exist»

If it is bash scripting you are wondering about, something like this would work:

if [ ! -f "$FILENAME" ]; then python daemon.py restart fi 

A better option may be to look into lockfile

The other answers are fine for detecting the existence of the file. However for a complete solution you probably should check that the PID in the pidfile is still running, and that it’s your program.

Another approach to solving the problem is a script that ensures that your daemon «stays» alive.

Something like this (note: signal handling should be added for proper startup/shutdown):

$PIDFILE = "/path/to/pidfile" if [ -f "$PIDFILE" ]; then echo "Pid file exists!" exit 1 fi while true; do # Write it's own pid file python your-server.py ; # force removal of pid in case of unexpected death. rm -f $PIDFILE; # sleep for 2 seconds sleep 2; done 

In this way, the server will stay alive even if it dies unexpectedly.

Источник

Проверка существования файла 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

Читайте также:  How to install icons on linux

Вначале команда 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