Linux проверить наличие папки

bash проверки существования файла, директории, пользователя

Вот так будет самый точный поиск пользователя:
grep «^test1:» /etc/passwd
grep «test1:» /etc/passwd
test1:x:999:1003:Hi the test1:/home/test1:/bin/bash
test-test1:x:997:1003:Hi the test-test1:/home/test1:/bin/false
test1www:x:996:1003:Hi the test1www:/home/test1:/bin/false
[email protected]:~# grep «^test1:» /etc/passwd
test1:x:999:1003:Hi the test1:/home/test1:/bin/bash

Эм, а на практике проверял код?
Только что создал тестовый файлик с кодом
grep «test2» /etc/passwd >/dev/null
if [ $? -ne 0 ]; then
echo ‘No username found’
fi
проверяем:
[email protected]:~$ bash usr.sh
No username found
[email protected]:~$ sh usr.sh
No username found

Проверка существования пользователя не точная:
если существует пользователь, например, test2
А grep ищем несуществующего пользователя test, то его найдет.

Добавить комментарий Отменить ответ

Теги

Категории

Похожие записи

Как через консоль удалить папку или каталог в linux

Команда Linux для удаления папки или каталога такая же, как и для удаления файла. Вы можете использовать команду rm для…

(httpd), uid 0: exited on signal 11 (core dumped) бага php и ffmpeg

Недавно на одном из медиа серверов нашел очень интересную багу, начал вылетать апач с ошибкой: (httpd), uid 0: exited on…

nginx и htpasswd онлайн генерация

Понадобилось недавно заблокировать директорию на сервере nginx паролем. Для этого необходимо в каждую секцию location добавить записи: auth_basic «Restricted»; auth_basic_user_file…

Источник

How To Check If File or Directory Exists in Bash

When working with Bash and shell scripting, you might need to check whether a directory or a file exists or not on your filesystem.

Based on this condition, you can exit the script or display a warning message for the end user for example.

In order to check whether a file or a directory exists with Bash, you are going to use “Bash tests”.

In this tutorial, you are going to learn how to check if a file or directory exists in a Bash script.

Читайте также:  Pyserial как установить linux

Check If File Exists

In order to check if a file exists in Bash, you have to use the “-f” option (for file) and specify the file that you want to check.

if [[ -f ]] then echo " exists on your filesystem." fi

For example, let’s say that you want to check if the file “/etc/passwd” exists on your filesystem or not.

In a script, you would write the following if statement.

#!/bin/bash if [[ -f "/etc/passwd" ]] then echo "This file exists on your filesystem." fi

check if file exists using bash script

Check File Existence using shorter forms

In some cases, you may be interested in checking if a file exists or not directly in your Bash shell.

In order to check if a file exists in Bash using shorter forms, specify the “-f” option in brackets and append the command that you want to run if it succeeds.

[[ -f ]] && echo "This file exists!" [ -f ] && echo "This file exists!"

Using the example used before, if you want to check if the “/etc/passwd” file exists using shorter forms, you write the following command

[[ -f /etc/passwd ]] && echo "This file exists!"

check if file exists using shorter form

So how does this command work?

Shorter forms are closely related to exit statuses.

When you run a command on Bash, it always exits with an error status : 0 for error and numbers greater than 0 for errors (1, 2.. 6 and so on)

In this case, the “&&” syntax will check if the exit status of the command on the left is equal to zero : if this is the case, it will execute the command on the right, otherwise it won’t execute it.

Protip : you can use “echo $” in order to see the exit status of the latest command run

Checking multiple files

In some cases, you may want to check if multiple files exist on your filesystem or not.

In order to check if multiple files exist in Bash, use the “-f” flag and specify the files to be checked separated by the “&&” operator.

if [[ -f ]] && [[ -f ]] then echo "They exist!" fi

Check If File Does Not Exist

On the other hand, you may want to check if a file does not exist on your filesystem.

Читайте также:  Обработка аудио файлов linux

In order to check if a file does not exist using Bash, you have to use the “!” symbol followed by the “-f” option and the file that you want to check.

if [[ ! -f ]] then echo " does not exist on your filesystem." fi

Similarly, you can use shorter forms if you want to quickly check if a file does not exist directly in your terminal.

[[ ! -f ]] && echo "This file does not exist!" [ ! -f ] && echo "This file does not exist!"

check if a file does not exist in bash

Note that it is also possible to check if a file does not exist using the “||” operator.

The “||” operator will execute the command on the right if and only if the command on the left fails (i.e exits with a status greater than zero).

To test if a file does not exist using the “||” operator, simply check if it exists using the “-f” flag and specify the command to run if it fails.

[[ -f ]] || echo "This file does not exist!"

Check If Directory Exists

In order to check if a directory exists in Bash, you have to use the “-d” option and specify the directory name to be checked.

if [[ -d "$DIRECTORY" ]] then echo "$DIRECTORY exists on your filesystem." fi

As an example, let’s say that you want to check with Bash if the directory /etc exists on your system.

In order to check its existence, you would write the following Bash script

#!/bin/bash if [[ -d /etc ]] then echo "/etc exists on your filesystem." fi

When executing this script, you would get the following output

Output $ /etc exists on your filesystem

Check Directory Existence using shorter forms

In some cases, you may be interested in checking if a directory exists or not directly in your Bash shell.

In order to check if a directory exists in Bash using shorter forms, specify the “-d” option in brackets and append the command that you want to run if it succeeds.

[[ -d ]] && echo "This directory exists!" [ -d ] && echo "This directory exists!"

Let’s say that you want to check if the “/etc” directory exists for example.

Читайте также:  Linux как узнать драйвер видеокарты

Using the shorter syntax, you would write the following command.

[ -d /etc ] && echo "This directory exists!"

check directory exists using short bash syntax

Creating a complete Bash script

If you find yourself checking multiple times per day whether a file (or multiple) exists or not on your filesystem, it might be handy to have a script that can automate this task.

In this section, you are going to create a Bash script that can take multiple filenames and return if they exist or not.

If they don’t, a simple notification message will be displayed on the standard output.

Create a new Bash script and make it executable using chmod.

$ mkdir -p ~/bin $ cd ~/bin && touch check_file && chmod u+x check_file && vi check_file

Here is the content of the script to be used to dynamically check if files exist.

#!/bin/bash # Using argument expansion to capture all files provided as arguments. for FILE in $ do if [[ ! -f $FILE ]] then echo "The file $ does not exist!" fi done

Save your script and add the “bin” folder you just created to your PATH environment variable.

$ export PATH="~/bin:$PATH" $ printenv PATH ~/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Now that your script is accessible wherever you are on the system, you can call your script and start checking if files exist or not.

$ check_file /etc/passwd /etc/pass /etc/file The file /etc/pass does not exist! The file /etc/file does not exist!

You created a custom to check whether files exist on your filesystem or not.

Conclusion

In this tutorial, you learnt how you can check if a file exists or not using Bash tests and Bash short syntax.

Similarly, you learnt how it is possible to verify if a directory exists.

Finally, you have written a complete Bash script that accepts dynamic arguments in order to check if multiple files exist or not.

If you are interested in Bash programming or in Linux System administration, we have a complete section dedicated to it on the website, so make sure to check it out!

Источник

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