Linux if files exist

Check if file exists [BASH]

Any ideas please? I will be glad for any help. P.S. I wish I could show the entire file without the risk of being fired from school for having a duplicate. If there is a private method of communication I will happily oblige. My mistake. Fas forcing a binary file into a wrong place. Thanks for everyone’s help.

4 Answers 4

Little trick to debugging problems like this. Add these lines to the top of your script:

The set -xv will print out each line before it is executed, and then the line once the shell interpolates variables, etc. The $PS4 is the prompt used by set -xv . This will print the line number of the shell script as it executes. You’ll be able to follow what is going on and where you may have problems.

Here’s an example of a test script:

#! /bin/bash export PS4="\$LINENO: " set -xv FILE1="$" # Line 6 if [ ! -e "$FILE1" ] # Line 7 then echo "requested file doesn't exist" >&2 exit 1 else echo "Found File $FILE1" # Line 12 fi 

And here’s what I get when I run it:

$ ./test.sh .profile FILE1="$" 6: FILE1=.profile if [ ! -e "$FILE1" ] then echo "requested file doesn't exist" >&2 exit 1 else echo "Found File $FILE1" fi 7: [ ! -e .profile ] 12: echo 'Found File .profile' Found File .profile 

Here, I can see that I set $FILE1 to .profile , and that my script understood that $ . The best thing about this is that it works on all shells down to the original Bourne shell. That means if you aren’t running Bash as you think you might be, you’ll see where your script is failing, and maybe fix the issue.

I suspect you might not be running your script in Bash. Did you put #! /bin/bash on the top?

script.sh [-g] [-p] [-r FUNCTION_ID|-d FUNCTION_ID] FILE

You may want to use getopts to parse your parameters:

#! /bin/bash USAGE=" Usage: script.sh [-g] [-p] [-r FUNCTION_ID|-d FUNCTION_ID] FILE " while getopts gpr:d: option do case $option in g) g_opt=1;; p) p_opt=1;; r) rfunction_id="$OPTARG";; d) dfunction_id="$OPTARG";; [?]) echo "Invalid Usage" 1>&2 echo "$USAGE" 1>&2 exit 2 ;; esac done if [[ -n $rfunction_id && -n $dfunction_id ]] then echo "Invalid Usage: You can't specify both -r and -d" 1>&2 echo "$USAGE" >2& exit 2 fi shift $(($OPTIND - 1)) [[ -n $g_opt ]] && echo "-g was set" [[ -n $p_opt ]] && echo "-p was set" [[ -n $rfunction_id ]] && echo "-r was set to $rfunction_id" [[ -n $dfunction_id ]] && echo "-d was set to $dfunction_id" [[ -n $1 ]] && echo "File is $1" 

Источник

Читайте также:  Command to gzip in linux

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

Читайте также:  Цвет шрифта консоль linux

#!/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.

Источник

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.

Читайте также:  Смонтировать ntfs раздел linux

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.

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.

Источник

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