Linux find bash script

Команда find в Linux – мощный инструмент сисадмина

Иногда критически важно быстро найти нужный файл или информацию в системе. Порой можно ограничиться стандартами функциями поиска, которыми сейчас обладает любой файловый менеджер, но с возможностями терминала им не сравниться.

Команда find – это невероятно мощный инструмент, позволяющий искать файлы не только по названию, но и по:

  • Дате добавления.
  • Содержимому.
  • Регулярным выражениям.

Данная команда будет очень полезна системным администраторам для:

  • Управления дисковым пространством.
  • Бэкапа.
  • Различных операций с файлами.

Команда find в Linux производит поиск файлов и папок на основе заданных вами критериев и позволяет выполнять действия с результатами поиска.

Синтаксис команды find:

  • directory-to-search (каталог поиска) – это отправной каталог, с которой find начинает поиск файлов по всем подкаталогам, которые находятся внутри. Если не указать путь, тогда поиск начнется в текущем каталоге;
  • criteria (критерий) – критерий, по которым нужно искать файлы;
  • action (действие) – что делать с каждым найденным файлом, соответствующим критериям.

Поиск по имени

Следующая команда ищет файл s.txt в текущем каталоге:

  • . (точка) – файл относится к нынешнему каталогу
  • -name – критерии по которым осуществляется поиск. В данном случае поиск по названию файла.

В данном случае критерий -name учитывает только символы нижнего регистра и файл S.txt не появиться в результатах поиска. Чтобы убрать чувствительность к регистру необходимо использовать –iname.

Для поиска всех изображений c расширением .png нужно использовать шаблон подстановки *.png:

Можно использовать название каталога для поиска. Например, чтобы с помощью команды find найти все png изображения в каталоге home:

Если выдает слишком много ошибок в отказе разрешения, тогда можно добавить в конец команды – 2> /dev/null. Таким образом сообщения об ошибках будут перенаправляться по пути dev/null, что обеспечит более чистую выдачу.

Поиск по типу файла

Критерий -type позволяет искать файлы по типу, которые бывают следующих видов:

  • f – простые файлы;
  • d – каталоги;
  • l – символические ссылки;
  • b – блочные устройства (dev);
  • c – символьные устройства (dev);
  • p – именованные каналы;
  • s – сокеты;

Например, указав критерий -type d будут перечислены только каталоги:

Поиск по размеру файла

Допустим, что вам необходимо найти все большие файлы. Для таких ситуаций подойдет критерий -size.

  • «+» — Поиск файлов больше заданного размера
  • «-» — Поиск файлов меньше заданного размера
  • Отсутствие знака означает, что размер файлов в поиске должен полностью совпадать.

В данном случае поиск выведет все файлы более 1 Гб (+1G).

Единицы измерения файлов:

Поиск пустых файлов и каталогов

Критерий -empty позволяет найти пустые файлы и каталоги.

Поиск времени изменения

Критерий -cmin позволяет искать файлы и каталоги по времени изменения. Для поиска всех файлов, измененных за последний час (менее 60 мин), нужно использовать -60:

Таким образом можно найти все файлы в текущем каталоге, которые были созданы или изменены в течение часа (менее 60 минут).

Для поиска файлов, которые наоборот были изменены в любое время кроме последнего часа необходимо использовать +60.

Поиск по времени доступа

Критерий -atime позволяет искать файлы по времени последнего доступа.

Таким образом можно найти файлы, к которым не обращались последние полгода (180 дней).

Читайте также:  Восстановить загрузочный том mac os

Поиск по имени пользователя

Опция –user username дает возможность поиска всех файлов и каталогов, принадлежащих конкретному пользователю:

Таким образом можно найти все файлы пользователя tisha в каталоге home, а 2>/dev/null сделает выдачу чистой без ошибок в отказе доступа.

Поиск по набору разрешений

Критерий -perm – ищет файлы по определенному набору разрешений.

Поиск файлов с разрешениями 777.

Операторы

Для объединения нескольких критериев в одну команду поиска можно применять операторы:

Например, чтобы найти файлы размером более 1 Гбайта пользователя tisha необходимо ввести следующую команду:

Если файлы могут принадлежать не только пользователю tisha, но и пользователю pokeristo, а также быть размером более 1 Гбайта.

Перед скобками нужно поставить обратный слеш «\».

Действия

К команде find можно добавить действия, которые будут произведены с результатами поиска.

  • -delete — Удаляет соответствующие результатам поиска файлы
  • -ls — Вывод более подробных результатов поиска с:
    • Размерами файлов.
    • Количеством inode.
  • -print Стоит по умолчанию, если не указать другое действие. Показывает полный путь к найденным файлам.
  • -exec Выполняет указанную команду в каждой строке результатов поиска.

-delete

Полезен, когда необходимо найти и удалить все пустые файлы, например:

Перед удалением лучше лишний раз себя подстраховать. Для этого можно запустить команду с действием по умолчанию -print.

Данное действие является особенным и позволяет выполнить команду по вашему усмотрению в результатах поиска.

  • command – это команда, которую вы желаете выполнить для результатов поиска. Например:
    • rm
    • mv
    • cp
  • <> – является результатами поиска.
  • \; — Команда заканчивается точкой с запятой после обратного слеша.

С помощью –exec можно написать альтернативу команде –delete и применить ее к результатам поиска:

Другой пример использования действия -exec:

Таким образом можно скопировать все .jpg изображения в каталог backups/fotos

Заключение

Команду find можно использовать для поиска:

  • Файлов по имени.
  • Дате последнего доступа.
  • Дате последнего изменения.
  • Имени пользователя (владельца файла).
  • Имени группы.
  • Размеру.
  • Разрешению.
  • Другим критериям.

С полученными результатами можно сразу выполнять различные действия, такие как:

  • Удаление.
  • Копирование.
  • Перемещение в другой каталог.

Команда find может сильно облегчить жизнь системному администратору, а лучший способ овладеть ей – больше практиковаться.

Источник

How To Run the .sh File Shell Script In Linux / UNIX

I have downloaded software for my Linux or Unix-like system from the Internet. There is a file called install.sh. How do I run an .sh file to install the software in macOS? How do your run .sh files from command line?

You can open or run .sh file in the terminal on Linux or Unix-like system. The .sh file is nothing but the shell script to install given application or to perform other tasks under Linux and UNIX like operating systems. The easiest way to run .sh shell script in Linux or UNIX is to type the following commands. Open the terminal (your shell prompt) and type the commands.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux or Unix-like systems
Est. reading time 3 mintues

How do I run .sh file shell script in Linux?

The procedure to run the .sh file shell script on Linux is as follows:

  1. Open the Terminal application on Linux or Unix
  2. Create a new script file with .sh extension using a text editor
  3. Write the script file using nano script-name-here.sh
  4. Set execute permission on your script using chmod command :
    chmod +x script-name-here.sh
  5. To run your script :
    ./script-name-here.sh
    Another option is as follows to execute shell script:
    sh script-name-here.sh
    OR bash script-name-here.sh

Let us see script examples and usage in details.

Syntax

The syntax is:
sh file.sh
OR
bash file.sh

How to run .sh file as root user

Some time you need root access to install application; without root, you won’t have the necessary permissions to install application or make system level modifications. Root access is disabled by default on many Linux and UNIX like systems. Simply use the sudo or su command as follows:
sudo bash filename.sh
Type your password. Another option is to use the su command as follows to become superuser:
su —
Type root user password and finally run your script:
bash filename.sh

How to use chmod command to run .sh shell script in Linux

Another recommend option is to set an executable permission using the chmod command as follows:
chmod +x file.sh
Now your can run your .sh file as follows
./file.sh
/path/to/file.sh

  • 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

Join Patreon

How do I run .sh file named install.sh?

Just run the following two command:
chmod +x install.sh
./install.sh
The dot (.) refers to the current working directory. The install.sh is in the current directory so you run it as above or as follows too:
bash install.sh
OR
sh install.sh

GUI method to run .sh file

  1. Select the file using mouse.
  2. Right-click on the file.
  3. Choose Properties:
  4. Click Permissions tab.
  5. Select Allow executing file as a program:
  6. Now click the file name and you will be prompted. Select “Run in the terminal” and it will get executed in the terminal.

Running .sh file shell script and debugging options

Pass the -x to debug shell script when running on your system. It print commands and their arguments as they are executed. For example:
bash -x script-name.sh
sh -x script-name.sh
Want to show shell input lines as they are read. Try passing the -v option:
bash -v script-name
We can combine both options. In other words, try it as follows:
bash -x -v backup.sh
For more information see how to improve your bash/sh shell script with ShellCheck lint script analysis tool and other bash debugging hints here.

Conclusion

You learned how to run .sh file shell script using combination of the chomod and dot (.) or sh/bash command. We can use any one of the following command execute shell script on Linux and Unix-like systems:

See the following resources for more info:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

anybody tell by which coomand i will check the modified date of files/dir in linux o/s

date -s “2 OCT 2006 18:00:00”

if we want to install software from cd.. how should be the command? i’m the newbie

rashid, if you want to install software from the cd you should try synaptic package handler or apt-get .

if the software is usually from the cd it will tell you to insert it

How can i execute this command export PS1=”\[[33[01;32m\]\u@\h\[33[01;34m\] \W]\]#” from a .sh script for example and make it work ?

Hey Black_Ps`
There are a few ways to do this but if you are not familiar with some of the nuances of Linux, it might be easier to create a new folder to place the file in (or all of your scripts in) like home/username/Desktop/scripts (substituting the actual user name in place of username). The following instructions are based on Fedora 10 with GNOME desktop so if you are running a different Linux distro, you may or may not have a few slight variances. Once you have a good place to store your scripts, you can use the GUI to help with creation of the shell script. Next, click on the “Applications” menu and highlight “Accessories” and then select “Text Editor” Type the following command #!/bin/bash and then press the enter key. Now, type the command you listed into the text editor and then select the “Save As” option. Now name your file (highly recommended that you don’t name it with spaces and make the name all lower case to help with ease of use later) and save it to your new folder you created…remember to give it a .sh name extension. Now close the text editor and go back to the “Applications” menu and highlight “System Tools” and then select “Terminal”. Type the following command cd /home/username/Desktop/scripts (again substituting the actual user name in place of username). The command ls and then press the enter key. Did it return the name of your script as a file in that folder? If so, move on to the next step. If it did not, navigate to the folder where you saved this file and move it to the correct folder. Type the following command chmod 755 yourfilename.sh. That’s it, you now have an executable shell script that will execute your command. You can do so by double clicking on it from the GUI, calling it from the terminal like so bash /home/username/Desktop/scripts/yourfilename.sh or you could put it on the cron to run unattended if you needed to. I hope this helps some or at least points you in the right direction.

can you please expalin it more detailes.

Ok thanks i’ll give it a try

When i open the terminal in UNIX..something like interactive keyboard authentication bla.. bla.. is coming..nd its difficult me to go on typing my commands and navigating through the directors and files..how can i fix this. any idea…? any command? anything helpful will be highly appreciated. _thanks_

Источник

Читайте также:  Как узнать пароль от wifi если забыл windows 10
Оцените статью