Начало работы
Базовые команды для файлов
ls -la показывает все файлы, включая скрытые. cd ~ ведёт домой, cd - возвращает в предыдущий каталог. mkdir -p создаёт родительские каталоги по необходимости. Для непустых каталогов нужен rm -r.
# list files
ls -la # long format, all files
ls -lh # human-readable sizes
ls -lt # sort by modification time
# current directory
pwd
# change directory
cd /home/user
cd .. # go up one level
cd ~ # go home
cd - # go to previous directory
# create/remove directories
mkdir newdir
mkdir -p path/to/dir # create parents
rmdir emptydir
rm -r nonempty # remove recursivelyПолучение справки
man — основная система документации. Разделы: 1=команды, 2=системные вызовы, 3=библиотеки, 4=устройства, 5=форматы файлов, 8=администрирование. man -k (или apropos) ищет по описаниям. --help даёт краткую справку. tldr даёт практические примеры и ставится отдельно (npm install -g tldr).
# manual pages
man ls # full documentation
man 5 crontab # section 5 (file formats)
man -k password # search by keyword (apropos)
# info pages (GNU tools, more detailed)
info coreutils
info ls
# quick help flags
command --help
ls --help
git --help
# tldr: community cheat sheets (install separately)
tldr tar
tldr find
# whatis: one-line description
whatis ls
# where is the binary / source / man page
whereis python3История команд и сокращения
!! повторяет последнюю команду (sudo !! — классическое исправление «забыл sudo»). !N запускает команду N из истории. !$ — последний аргумент. Ctrl+R — интерактивный обратный поиск: нажмите ещё раз, чтобы найти более ранние совпадения. История хранится в ~/.bash_history; HISTSIZE задаёт размер в памяти, HISTFILESIZE — в файле.
# history expansion
history # show command history
!! # repeat last command
sudo !! # repeat last command as root
!42 # run command #42 from history
!ls # run last command starting with ls
!$ # last argument of last command
!!:gs/old/new/ # substitute in last command
# search history (interactive)
# Ctrl+R then type to search backward
# clear history
history -c # clear current session
# edit ~/.bashrc HISTSIZE and HISTFILESIZE
# save and reload history
history -a # append to history file
history -r # reload from fileТипы файлов и определение
file читает magic bytes файла и определяет истинный тип — куда надёжнее расширения. ls -F добавляет индикаторы типа (* исполняемый, / каталог, @ symlink, = сокет). stat показывает полные метаданные inode, включая все три отметки времени: Access (atime), Modify (mtime, содержимое), Change (ctime, метаданные).
# identify file type by content (not extension)
file document.pdf # PDF document
file image.png # PNG image data
file script.sh # ASCII text executable
file /bin/ls # ELF 64-bit LSB executable
# file with multiple files
file *.txt
# show MIME type
file --mime-type video.mp4 # video/mp4
# ls -F shows type indicator
ls -F
# file* (executable)
# dir/ (directory)
# link@ (symlink)
# socket= (socket)
# stat: detailed file info
stat file.txt
# Size, Blocks, IO Block, Device, Inode, Links,
# Access/Modify/Change/Birth timesСокращения навигации в терминале
Эти сокращения Readline работают в bash и большинстве оболочек. Ctrl+A/E прыгают в начало и конец строки. Ctrl+W/U/K удаляют текст, Ctrl+Y вставляет обратно (kill ring). Ctrl+R ищет по истории. Ctrl+L очищает экран. Ctrl+S замораживает вывод (частая причина «зависшего терминала» — Ctrl+Q возобновляет). Выучите их, чтобы заметно ускорить редактирование команд.
# cursor movement
Ctrl+A # move to beginning of line
Ctrl+E # move to end of line
Ctrl+B # move back one char
Ctrl+F # move forward one char
# editing
Ctrl+D # delete char under cursor (or EOF/exit)
Ctrl+H # delete char before cursor (backspace)
Ctrl+W # delete word before cursor
Ctrl+U # delete from cursor to beginning
Ctrl+K # delete from cursor to end
Ctrl+Y # paste (yank) deleted text back
# job control
Ctrl+C # send SIGINT (interrupt)
Ctrl+Z # suspend (send SIGTSTP)
Ctrl+D # end of input / exit shell
# screen
Ctrl+L # clear screen (same as clear)
Ctrl+S # stop output (freeze)
Ctrl+Q # resume output
# Alt shortcuts
Alt+B / Alt+F # move back/forward by word
Alt+Backspace # delete word backwardПеременные окружения
Переменные окружения наследуются дочерними процессами при export. $PATH определяет, где оболочка ищет команды: каталоги перебираются по порядку через двоеточие. ~/.bashrc читается для интерактивных не-login оболочек; ~/.profile или ~/.bash_profile — для login. После правки всегда выполняйте source файла. printenv VAR проверяет одну переменную без раскрытия.
# view all environment variables
env
printenv
# view specific variable
echo $HOME
echo $PATH
echo $USER
# set a variable (current shell only)
MYVAR="hello"
echo $MYVAR
# export to child processes
export PATH="$PATH:/opt/bin"
export EDITOR=nano
# set and export in one step
export MYVAR="hello"
# unset a variable
unset MYVAR
# common variables
# $HOME user home directory
# $PATH command search path
# $USER current username
# $SHELL current shell path
# $PWD current working directory
# $OLDPWD previous directory
# $PS1 prompt string
# persistent: add to ~/.bashrc or ~/.profile
echo 'export EDITOR=vim' >> ~/.bashrc
source ~/.bashrcОперации с файлами
Копирование файлов (cp)
cp копирует файлы. Для каталогов нужен -r (или -R). -i спрашивает перед перезаписью (рекомендуется против потери данных). -p сохраняет метаданные; -a — режим архива (сохраняет всё, включая symlink, идеально для бэкапов). -u обновляет, только если источник новее. В скриптах, где перезапись опасна, всегда используйте -i.
# copy a file
cp source.txt dest.txt
# copy to a directory
cp file.txt /backup/
# copy multiple files to a directory
cp file1.txt file2.txt /backup/
# copy directories recursively
cp -r src_dir/ dest_dir/
# interactive (prompt before overwrite)
cp -i file.txt /backup/
# preserve attributes (timestamps, permissions, ownership)
cp -p file.txt /backup/
cp -a src_dir/ dest_dir/ # archive mode (-rdp)
# only copy if source is newer
cp -u file.txt /backup/
# verbose (show what is being copied)
cp -v file.txt /backup/
# force overwrite
cp -f file.txt /backup/Перемещение и переименование (mv)
mv — и перемещение, и переименование: он меняет запись каталога без копирования данных (мгновенно в пределах одной файловой системы). -i спрашивает перед перезаписью. mv -n не даёт перезаписать существующие файлы. Команда rename (на Perl в Debian/Ubuntu) использует regex для массового переименования — гораздо мощнее циклов с mv. Учтите: синтаксис rename различается между дистрибутивами (util-linux и perl версии).
# rename a file
mv oldname.txt newname.txt
# move file to another directory
mv file.txt /target/dir/
# move multiple files
mv file1.txt file2.txt /target/dir/
# interactive (prompt before overwrite)
mv -i file.txt /target/
# force overwrite
mv -f file.txt /target/
# no overwrite (don't replace existing)
mv -n file.txt /target/
# move only if newer
mv -u file.txt /target/
# verbose
mv -v olddir/ newdir/
# rename batch with rename command
rename 's/\.txt$/.md/' *.txt
rename .JPG .jpg *.JPGУдаление файлов (rm)
rm удаляет файлы безвозвратно (без корзины). Для каталогов нужен -r. -rf опасен: удаляет рекурсивно без вопросов; всегда перепроверяйте путь. Никогда не запускайте rm -rf / или rm -rf $VAR/, если $VAR может быть пустым. Для восстановимого удаления рассмотрите trash-cli. find -delete безопаснее для удаления по шаблону: сначала можно протестировать без -delete.
# remove a file
rm file.txt
# remove multiple files
rm file1.txt file2.txt
# interactive (prompt for each file)
rm -i file.txt
# force (ignore nonexistent, no prompt)
rm -f file.txt
# remove directory recursively
rm -r directory/
rm -rf directory/ # force + recursive (DANGEROUS)
# verbose
rm -v *.tmp
# remove files matching pattern
find . -name "*.bak" -delete
find . -name "*.log" -mtime +30 -delete
# safer alternative: trash-cli
trash-put file.txt
trash-list
trash-restoreСоздание файлов (touch)
touch создаёт пустые файлы или обновляет отметки времени существующих. Без опций он ставит atime и mtime в текущее время. -t задаёт конкретную отметку. -r копирует отметку у файла-образца. Для файла с содержимым используй те перенаправление (>) или here-document. touch часто применяют для заглушек или принудительной пересборки целей make.
# create an empty file
touch newfile.txt
# create multiple empty files
touch file1.txt file2.txt file3.txt
# update access and modification time to now
touch existing.txt
# set specific time (YYYYMMDDHHMM format)
touch -t 202401011200 file.txt # Jan 1, 2024 12:00
# set only access time
touch -a file.txt
# set only modification time
touch -m file.txt
# use time from another file
touch -r reference.txt target.txt
# create file with content
echo "content" > file.txt
cat > file.txt << 'EOF'
line 1
line 2
EOFЖёсткие и символические ссылки (ln)
Жёсткие ссылки делят один inode (данные): удаление одной не удаляет данные, пока не удалены ВСЕ ссылки. Они не могут пересекать файловые системы и ссылаться на каталоги. Символические ссылки — ссылки на путь: ломаются, если цель перемещена или удалена, но работают между файловыми системами и с каталогами. Для symlink используйте ln -s (самый частый вариант). readlink -f разрешает всю цепочку до реального файла.
# hard link (same inode, same filesystem only)
ln original.txt hardlink.txt
# symbolic link (symlink, path reference)
ln -s /path/to/target symlink_name
ln -s original.txt softlink.txt
# force recreate a symlink
ln -sf /new/target symlink_name
# symbolic link to a directory
ln -s /var/log /home/user/logs
# view link target
readlink symlink
readlink -f symlink # canonical absolute path
ls -l symlink # show what it points to
# find broken symlinks
find . -type l ! -exec test -e {} \; -print
# count hard links to a file
ls -li file.txt # 2nd column is link count
# remove a symlink
rm symlink_name
unlink symlink_nameМетаданные файлов (stat, basename, dirname)
stat показывает полные метаданные inode. basename и dirname разбирают путь — необходимо в скриптах, обрабатывающих списки файлов. realpath разрешает относительные пути и symlink в абсолютные канонические. stat -c задаёт свой формат вывода (%n=имя, %s=размер, %y=mtime, %a=восьмеричные права) — удобно в скриптах. Эти инструменты заменяют хрупкое раскрытие параметров для работы с путями.
# stat: full file information
stat file.txt
# Size: 1024 Blocks: 8 IO Block: 4096
# Device: 801h/2049d Inode: 1234567
# Links: 1
# Access: (0644/-rw-r--r--) Uid: 1000 Gid: 1000
# Access/Modify/Change: 2024-01-01 12:00:00
# custom format
stat -c '%n %s bytes' file.txt
stat -c '%y' file.txt # modification time
# basename: extract filename from path
basename /var/log/syslog # syslog
basename /var/log/syslog.log .log # syslog
# dirname: extract directory from path
dirname /var/log/syslog # /var/log
# realpath: resolve to absolute path
realpath ../file.txt
realpath -s symlink # physical path (no symlink resolution)
# file size only
stat -c %s file.txt # bytes
du -h file.txt | cut -f1 # human-readableОперации с каталогами
Создание каталогов (mkdir)
mkdir -p создаёт родительские каталоги по необходимости и не падает, если каталог уже есть, — необходимо для идемпотентных скриптов. -m сразу задаёт права (переопределяет umask). Раскрытие фигурных скобок ({a,b,c}) вместе с mkdir -p создаёт сложные деревья каталогов одной командой. Частый приём для создания структуры проекта.
# create a single directory
mkdir newdir
# create nested directories
mkdir -p path/to/deep/dir
# create multiple directories
mkdir dir1 dir2 dir3
# create with specific permissions
mkdir -m 755 publicdir
mkdir -m 700 privatedir
# verbose output
mkdir -v newdir
# create parent dirs with permissions
mkdir -p -m 755 /opt/myapp/{bin,lib,etc}
# create a directory tree at once
mkdir -p project/{src,tests,docs}
mkdir -p project/src/{main,utils}
mkdir -p project/{src/{main,utils},tests,docs}Удаление каталогов (rmdir, rm)
rmdir удаляет только пустые каталоги — безопасно, но ограниченно. rm -r удаляет непустые каталоги рекурсивно. rm -rf — ядерный вариант: всегда проверяйте путь. Приём find -empty -delete удаляет только пустые каталоги, не трогая заполненные. В скрипт ах всегда проверяйте, что переменная не пуста, перед rm -rf, чтобы случайно не удалить /.
# remove an empty directory
rmdir emptydir
# remove directory with contents
rm -r directory/
# force remove (no prompt)
rm -rf directory/
# remove empty directories recursively (find)
find . -type d -empty -delete
find . -type d -empty -exec rmdir {} \;
# remove directory with confirmation
rm -ri directory/
# safe removal pattern in scripts
DIR="/tmp/mydir"
if [ -n "$DIR" ] && [ -d "$DIR" ]; then
rm -rf "$DIR"
fi
# move to trash instead
trash-put directory/Список каталогов и tree
ls -d */ перечисляет только каталоги. tree рисует визуальную иерархию: -L ограничивает глубину, -I исключает шаблоны (крайне полезно для исключения node_modules/.git). Для больших деревьев сочетайте tree -d -L 2 для быстрого обзора. ls -1 (это цифра один) выводит по файлу на строку — удобно для передачи в wc -l для подсчёта.
# list directory contents
ls -la # all files, long format
ls -lh # human-readable sizes
ls -lt # sort by time (newest first)
ls -lS # sort by size (largest first)
ls -lr # reverse order
ls -R # recursive listing
ls -d */ # list only directories
# tree view (install separately: apt install tree)
tree # show directory tree
tree -L 2 # limit depth to 2
tree -d # directories only
tree -a # include hidden files
tree -h # show file sizes
tree --dirsfirst # dirs before files
tree -I 'node_modules|.git' # ignore patterns
tree -H . -o tree.html # output as HTML
# count files in directory
ls -1 | wc -l
find . -maxdepth 1 -type f | wc -lРазмер каталогов (du)
du измеряет занятое место. -s (итог) показывает только сумму, -h делает размеры читаемыми. du -sh */ даёт размеры непосредственных подкаталогов. sort -rh сортирует читаемые размеры по убыванию (крупнейшие первыми). --exclude пропускает шаблоны. Разница apparent-size и значений по умолчанию: apparent показывает логический размер файла, по умолчанию — реально выделенные блоки диска (могут быть больше из-за размера блока).
# size of current directory (total)
du -sh .
# size of specific directories
du -sh /var/log /tmp /home
# size of all subdirectories
du -sh */
# sort directories by size (largest first)
du -sh * | sort -rh
# find the 10 largest directories
du -sh * | sort -rh | head -10
# include hidden files/dirs
du -sh .[!.]*
# maximum depth
du -h --max-depth=1
du -h -d 1 # short form
# apparent size vs disk usage
du -sh --apparent-size file # logical size
du -sh file # actual disk blocks
# exclude directories
du -sh --exclude='*.log' .
du -sh --exclude=node_modules .Стек каталогов (pushd, popd)
pushd/popd управляют стеком каталогов: pushd сохраняет текущий каталог и переходит в новый; popd возвращает сохранённый. dirs показывает стек. Это мощнее cd - (который переключает только два каталога). Полезно в скриптах, которым нужно переходить между несколькими каталогами и возвращаться. Синтаксис +N поворачивает или удаляет по позиции.
# push directory onto stack and cd into it
pushd /var/log
# pushes current dir, then cd to /var/log
# push another
pushd /tmp
# stack: /tmp /var/log /home/user
# pop back to previous directory
popd
# returns to /var/log
# list the directory stack
dirs
dirs -v # verbose (numbered)
dirs -c # clear the stack
# navigate by index
pushd +2 # rotate to 3rd entry
popd +1 # remove 2nd entry
# practical: save current dir, work, return
pushd /etc
cp config.conf ~/backup/
popd # back to where we were
# alternative: use cd - for simple toggle
cd /var/log
cd - # back to previous directoryПросмотр файлов
cat и tac
cat выводит весь файл в stdout — годится для небольших файлов, для больших используйте less/head. cat -n нумерует строки. cat -A показывает скрытые символы (табуляции, окончания строк) — полезно для отладки форматирования. tac переворачивает порядок строк (cat наоборот). cat также используют для конкатенации файлов и перенаправления ввода. Для интерактивного просмотра больших файлов лучше less.
# display entire file
cat file.txt
# concatenate multiple files
cat file1.txt file2.txt > combined.txt
# display with line numbers
cat -n file.txt
# display with non-printing characters
cat -A file.txt # show tabs as ^I, line ends as $
cat -v file.txt # show non-printing chars
cat -e file.txt # show line ends as $
cat -t file.txt # show tabs as ^I
# append to a file
cat >> file.txt << 'EOF'
appended line
EOF
# tac: reverse line order
tac file.txt # last line first
# create file from stdin
cat > newfile.txt
# type content, Ctrl+D to endПейджер less
less — ст андартный пейджер, гораздо лучше more, потому что позволяет листать назад. Клавиши похожи на vim (j/k/g/G). / ищет вперёд, ? — назад. F включает «режим слежения» (как tail -f) для наблюдения за логами. less сам обрабатывает сжатые файлы при настроенном lesspipe. Нажатие v открывает текущий файл в $EDITOR для быстрой правки.
# view a file
less file.txt
# view command output
dmesg | less
ls -la /etc | less
# navigation inside less:
# space / f forward one page
# b backward one page
# j / k down / up one line
# g go to beginning
# G go to end
# /pattern search forward
# ?pattern search backward
# n next match
# N previous match
# v open in editor ($EDITOR)
# F follow mode (like tail -f)
# q quit
# useful flags
less -N file.txt # show line numbers
less -S file.txt # chop long lines
less -i file.txt # case-insensitive search
less +/pattern file.txt # open at first match
# view compressed files
less file.gz # auto-decompresses (if lesspipe installed)head и tail
head показывает начало файла, tail — конец. tail -f необходим для наблюдения за логами в реальном времени. tail -F (заглавная) переживает ротацию файлов (когда логи переименовывают и обрезают), переоткрывая файл. head -n -N показывает всё, кроме последних N строк. Для больших файлов head/tail мгновенны (не читают файл целиком).
# first 10 lines (default)
head file.txt
# last 10 lines (default)
tail file.txt
# first N lines
head -n 20 file.txt
head -20 file.txt
# last N lines
tail -n 20 file.txt
tail -20 file.txt
# all but last N lines
head -n -5 file.txt # all except last 5 lines
# first N bytes
head -c 100 file.txt
tail -c 100 file.txt
# follow a log file (live updates)
tail -f /var/log/syslog
# follow with retry (handles log rotation)
tail -F /var/log/app.log
# show last 5 lines, then follow
tail -n 5 -f app.log
# multiple files
tail -n 5 file1.txt file2.txtПросмотр отдельных строк
sed -n 'Np' выводит конкретные номера строк. awk с NR (номер записи) гибче для диапазонов и условий. Приём (head; tail) показывает оба конца большого файла. nl и cat -n нумеруют строки. hexdump/xxd показывают бинарные файлы в hex — необходимо для исследования не текстовых файлов, отладки форматов и восстановления данных.
# show line N (e.g., line 10)
sed -n '10p' file.txt
# show lines M to N
sed -n '10,20p' file.txt
awk 'NR>=10 && NR<=20' file.txt
# show first and last N lines
(head -5; echo "..."; tail -5) < file.txt
# show lines matching pattern
sed -n '/pattern/p' file.txt
awk '/pattern/' file.txt
# show every Nth line
awk 'NR % 3 == 0' file.txt # every 3rd line
sed -n '0~3p' file.txt # every 3rd line (GNU)
# number lines
nl file.txt
cat -n file.txt
grep -n "" file.txt
# show file in hex
hexdump -C file.bin
xxd file.bin
od -A x -t x1z file.binПодсчёт слов и строк (wc)
wc считает строки (-l), слова (-w), байты (-c), символы (-m, с учётом кодировки) и длину самой длинной строки (-L). При нескольких файлах показывает счётчики по каждому и итог. Приём grep | wc -l считает совпавшие строки, но grep -c эффективнее (без конвейера). Для подсчёта файлов ls -1 | wc -l быстр, но find точнее для рекурсивного подсчёта.
# count lines, words, and bytes
wc file.txt
# 10 50 300 file.txt
# lines words bytes
# count lines only
wc -l file.txt
# count words only
wc -w file.txt
# count characters only
wc -m file.txt
# count bytes only
wc -c file.txt
# count the longest line length
wc -L file.txt
# count files in a directory
ls -1 | wc -l
find . -type f | wc -l
# count total lines in multiple files
wc -l *.py
# count matching lines (grep + wc)
grep "error" log.txt | wc -l
# count unique lines
sort file.txt | uniq | wc -lПоиск файлов
find по имени и типу
find — самый мощный инструмент поиска файлов. -name совпадает с именами по шаблону; -iname без учёта регистра. -type фильтрует по типу (f=файл, d=каталог, l=symlink). -maxdepth ограничивает рекурсию (важно для производительности). -not и -prune исключают пути. \( -name A -o -name B \) группирует усл овия через ИЛИ. Всегда заключайте шаблоны в кавычки, чтобы оболочка их не раскрывала.
# search by name (case-sensitive)
find / -name "config.txt"
find . -name "*.py"
# case-insensitive name search
find . -iname "*.JPG"
# find by type
find . -type f -name "*.txt" # regular files
find . -type d -name "node_modules" # directories
find . -type l # symlinks
find . -type b # block devices
find . -type c # character devices
# find by path pattern
find . -path "*/src/*.test.js"
# find using regex (full path)
find . -regex ".*\.\(py\|js\)$"
# multiple name patterns
find . \( -name "*.py" -o -name "*.js" \)
# limit search depth
find . -maxdepth 2 -name "*.txt"
# exclude directories
find . -name "*.py" -not -path "*/venv/*"
find . -name "*.py" -prune -path "*/venv/*"find по времени и размеру
Поиск по времени: -mtime (дни), -mmin (минуты). Префикс - (меньше) и + (больше) задаёт сравнение. -atime — время доступа, -ctime — время изменения метаданных. Суффиксы размера: c (байты), k (КБ), M (МБ), G (ГБ). -perm 644 совпадает точно; -perm -u+x — файлы с правом выполнения для пользователя; /4000 — любой файл с SUID. Поиск SUID-файлов — приём аудита безопасности.
# modified within last N days
find . -mtime -7 # < 7 days ago
find . -mtime +30 # > 30 days ago
find . -mtime 7 # exactly 7 days ago
# modified within N minutes
find . -mmin -60 # last 60 minutes
# accessed time (-atime / -amin)
find /var/log -atime -1 # accessed in last 24h
# changed (metadata) time
find . -ctime -1
# by size
find . -size +100M # larger than 100MB
find . -size -1k # smaller than 1KB
find . -size 10M # exactly 10MB
# empty files and directories
find . -empty -type f
find . -empty -type d
# by permissions
find . -perm 644 # exactly 644
find . -perm -u+x # has user execute
find / -perm /4000 2>/dev/null # SUID files (security audit)
# combine: large files modified recently
find /var/log -size +10M -mtime -7find -exec и -delete
-exec выполняет команду для каждого результата. {} — заглушка имени файла; \; выполняет команду на каждый файл; + группирует файлы (эффективнее, меньше порождения процессов). -delete безопаснее -exec rm, потому что атомарен. Всегда сначала проверяйте с -print перед добавлением -delete. -ok спрашивает подтверждение на каждый файл. Паттерн dirs-755-files-644 — стандартные права для веб-сервера.
# execute a command on each result (one per file)
find . -name "*.log" -exec ls -lh {} \;
# execute with + (batch, more efficient)
find . -name "*.log" -exec ls -lh {} +
# delete matched files
find /tmp -name "*.tmp" -type f -delete
# safer: delete with confirmation
find . -name "*.bak" -ok rm {} \;
# find and grep
find . -name "*.py" -exec grep "TODO" {} +
# find and chmod
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
# find and compress old logs
find /var/log -name "*.log" -mtime +30 -exec gzip {} \;
# find and move
find . -name "*.jpg" -exec mv {} /photos/ \;
# print then delete (verification)
find . -name "*.tmp" -print -deletelocate и which
locate ищет по заранее построенной базе (обновляется updatedb, обычно через cron) — намного быстрее find, но может устареть. Для обновления запустите sudo updatedb. which находит исполняемые файлы в $PATH. whereis также находит исходники и man-страницы. type показывает, как оболочка разрешает команду (алиас, встроенная или файл), — точнее which для встроенных команд. command -v — POSIX-переносимый способ.
# locate: fast file search using a pre-built database
locate config.txt
locate "*.conf"
locate -i readme # case-insensitive
locate -r "^/usr.*\.py$" # regex
locate -n 10 "*.log" # limit to 10 results
locate -c "*.py" # count matches only
# update the database (run as root)
sudo updatedb
# which: find a command's binary location
which python3 # /usr/bin/python3
which -a python3 # all matches in PATH
# whereis: binary, source, and man page
whereis python3
# python3: /usr/bin/python3 /usr/lib/python3 /usr/share/man/man1/python3.1.gz
# type: show how a command is resolved
type ls # ls is aliased to 'ls --color=auto'
type cd # cd is a shell builtin
type python3 # python3 is /usr/bin/python3
# find command in PATH
command -v python3Практические рецепты find
Эти рецепты показывают реальную силу find. -printf задаёт свой формат вывода (%s=размер, %p=путь). -newermt сопоставляет по времени изменения с датой-строкой. -newer сравнивает с файлом-образцом. Поиск битых symlink использует test -e внутри -exec. Рецепт подсчёта файлов по расширению — классический конвейер из find, sed, sort и uniq для быстрого анализа кодовой базы.
# find the 10 largest files
find . -type f -exec ls -lhS {} + | head -10
find . -type f -printf '%s %p\n' | sort -rn | head -10
# find recently modified files (last 24h)
find /etc -mtime -1 -type f
# find files owned by a specific user
find /home -user alice -type f
find / -group developers -type f 2>/dev/null
# find files modified between two times
find . -newermt "2024-01-01" ! -newermt "2024-06-01"
# find files newer than a reference file
find . -newer reference.txt
# find and list with details
find . -name "*.conf" -exec ls -la {} \;
# find all broken symlinks
find . -type l ! -exec test -e {} \; -print
# find files with specific permissions
find /www -type f -perm 644 -exec chmod 664 {} \;
# count files by extension
find . -type f | sed 's/.*\.//' | sort | uniq -c | sort -rnПоиск по тексту (grep)
Базовые шаблоны grep
grep находит строки, соответствующие шаблону. -i игнорирует регистр, -w совпадает с целыми словами, -v инвертирует, -c считает, -n нумерует строки, -l выводит имена файлов, -h скрывает имена файлов, -o показывает только совпадение. По умолчанию grep использует Basic Regex (BRE); -E включает Extended Regex (чище синтаксис), -F — фиксированные строки (быстрее, без regex).
# basic search (literal string)
grep "error" logfile.txt
# case-insensitive
grep -i "error" logfile.txt
# whole word match (avoids matching 'errors')
grep -w "error" log.txt
# invert match (lines NOT matching)
grep -v "debug" log.txt
# count matching lines
grep -c "error" log.txt
# show line numbers
grep -n "error" log.txt
# multiple files (shows filename:line)
grep "error" *.log
# suppress filename prefix
grep -h "error" *.log
# only show filenames with matches
grep -l "error" *.log
# only show matched portion
grep -o "https?://[^ ]+" urls.txtgrep с регулярными выражениями
grep -E (или egrep) использует расширенные регулярные выражения, где +, ?, |, () работают без обратных косых. ^ и $ якорят начало и конец строки. [] задаёт классы символов, {} — повторения. -P включает Perl-совместимые regex (PCRE) с \d, \w, \b и lookaround — мощно, но специфично для GNU. -F трактует шаблон как фиксированную строку (без regex), быстрее для буквального поиска.
# extended regex (-E or egrep)
grep -E "error|warning|fatal" log.txt
# anchors
grep -E "^ERROR:" log.txt # lines starting with ERROR:
grep -E "completed$" log.txt # lines ending with completed
# character classes
grep -E "[0-9]{4}-[0-9]{2}-[0-9]{2}" dates.txt
grep -E "[A-Z][a-z]+" names.txt
# quantifiers
grep -E "ab+c" file.txt # one or more b
grep -E "ab*c" file.txt # zero or more b
grep -E "ab?c" file.txt # zero or one b
# alternation and grouping
grep -E "(cat|dog) food" file.txt
# PCRE (-P, GNU grep only)
grep -P "\d{3}-\d{4}" phones.txt
grep -P "(?<=foo)bar" file.txt # lookbehind
# fixed string (no regex, faster for literals)
grep -F "literal$string" file.txtКонтекст и вывод grep
Флаги контекста (-B, -A, -C) показывают окружающие строки — необходимо для понимания записей логов. --color подсвечивает совпадения. -r ищет рекурсивно (без symlink); -R следует symlink. --include/--exclude/--exclude-dir фильтруют, какие файлы искать: всегда исключайте node_modules и .git. -a заставляет считать бинарные файлы текстом; -I пропускает их. -rn сочетает рекурсию с номерами строк.
# show context lines
grep -B 2 "error" log.txt # 2 lines Before
grep -A 3 "error" log.txt # 3 lines After
grep -C 2 "error" log.txt # 2 lines Context (both)
# color highlight
grep --color=auto "error" log.txt
# recursive search
grep -r "TODO" ./src/
grep -R "TODO" ./src/ # follows symlinks
# include/exclude file patterns
grep -r --include="*.py" "import" .
grep -r --exclude="*.test.js" "TODO" .
grep -r --exclude-dir=node_modules "TODO" .
# binary files
grep -a "pattern" binary_file # treat as text
grep -I "pattern" . # skip binary files
# output only the match
grep -oE "[0-9.]+" data.txt
# line numbers in recursive search
grep -rn "function" src/grep в конвейерах
Приём [n]ginx не даёт grep совпасть с собственным процессом: скобки ломают совпадение с буквальной строкой 'grep' в списке процессов. zgrep ищет в сжатых файлах. pgrep — специализированный поиск процессов. grep -rl перечисляет файлы, содержащие шаблон; передача в xargs grep ищет в этих файлах другой шаблон — типичный приём «археологии кода».
# search command output
ps aux | grep nginx
ps aux | grep "[n]ginx" # trick: prevents matching grep itself
# search compressed logs
zcat log.gz | grep "error"
zgrep "error" log.gz # direct search
# chain multiple greps
cat log.txt | grep "error" | grep -v "timeout"
# extract and filter
grep -oE "[0-9.]+" response.txt | sort -n | uniq
# find processes (better than ps | grep)
pgrep -f "node server.js"
pgrep -fl "node" # full command line
# search history
history | grep "git rebase"
# find files containing pattern, then search more
grep -rl "config" . | xargs grep "database"
# count errors per hour
grep "ERROR" log.txt | grep -oE "[0-9]{2}:" | sort | uniq -c
# search and show filename + line
grep -rn "TODO" src/ | head -20Код возврата grep и скрипты
Код возврата grep делает его идеальным для скриптов: 0 (совпадение найдено), 1 (нет совпадения), 2 (ошибка). -q подавляет вывод для чисто условных проверок. В скриптах с set -e grep, вернувший 1 (нет совпадения), завершит скрипт — используйте '|| true'. grep -c возвращает число. Эта скриптовая природа делает grep строительным блоком для мониторинга логов, валидации и проверок CI/CD.
# grep exit codes: 0=match, 1=no match, 2=error
if grep -q "error" /var/log/syslog; then
echo "Errors found!"
# send alert, trigger recovery
fi
# silent check (-q), no output
grep -q "^$" file.txt && echo "has blank lines"
# count and branch
errors=$(grep -c "ERROR" log.txt)
if [ "$errors" -gt 10 ]; then
echo "Too many errors: $errors"
fi
# use in while loop
grep "pattern" file.txt | while read -r line; do
echo "Found: $line"
done
# grep with set -e (prevents exit on no-match)
set -e
grep "missing" file.txt || true
# validate input with grep
if echo "$input" | grep -qE "^[0-9]+$"; then
echo "valid number"
firipgrep (rg) — современная альтернатива
ripgrep (rg) — современная быстрая альтернатива grep для поиска по коду. Он рекурсивен по умолчанию, уважает .gitignore и значительно быстрее. -t/-T фильтруют по типу файла (встроенные определения типов). -g использует шаблоны glob. В отличие от grep, rg по умолчанию пропускает скрытые и gitignored файлы — используйте --hidden и --no-ignore, чтобы это отменить. Установка: cargo install ripgrep или apt install ripgrep.
# basic search (recursive by default)
rg "pattern" # searches current dir
rg "pattern" src/ # search specific dir
# case-insensitive
rg -i "error"
# whole word
rg -w "error"
# show context
rg -C 3 "pattern" # 3 lines context
rg -B 2 -A 2 "pattern" # before and after
# file type filter
rg "TODO" -t py # Python files only
rg "TODO" -t py -t js # Python and JavaScript
rg "TODO" -T md # exclude Markdown
# glob patterns
rg "pattern" -g "*.py"
rg "pattern" -g "!tests/*" # exclude tests
# fixed string (no regex)
rg -F "literal$string"
# list files with matches
rg -l "pattern"
# count matches
rg -c "pattern"
# search hidden files
rg --hidden "pattern"
# multiline search
rg -U "start.*end" # dot matches newlinesОбработка текста
sed — потоковый редактор
sed неинтерактивно редактирует текстовые потоки. s заменяет (g для глобально); d удаляет; p печатает. -i правит на месте (всегда сначала тестируйте без -i или используйте -i.bak для бэкапа). Разделителем может быть любой символ — берите | или # для путей, чтобы не экранировать слэши. -E включает расширенные regex с более чистым синтаксисом групп захвата. sed обрабатывает построчно.
# substitute (replace first occurrence per line)
sed 's/old/new/' file.txt
# substitute all occurrences (global)
sed 's/old/new/g' file.txt
# case-insensitive (GNU sed)
sed 's/old/new/gi' file.txt
# in-place editing
sed -i 's/old/new/g' file.txt
sed -i.bak 's/old/new/g' file.txt # keep backup
# delete lines
sed '/^#/d' file.txt # delete comment lines
sed '/^$/d' file.txt # delete blank lines
sed '5d' file.txt # delete line 5
sed '5,10d' file.txt # delete lines 5-10
# print specific lines
sed -n '10,20p' file.txt # lines 10-20
sed -n '/pattern/p' file.txt # matching lines
# different delimiter for paths
sed 's|/usr/local|/opt|g' paths.txt
# extended regex with capture groups
sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\3\/\2\/\1/' dates.txt
# multiple commands
sed -e 's/a/A/g' -e 's/b/B/g' file.txtawk — обработка колонок
awk — мини-язык программирования для табличных данных. $1, $2... — поля; $0 — вся строка; $NF — последнее поле. -F задаёт разделитель входа; OFS — выхода. BEGIN выполняется до обработки, END — после. NR — номер записи (строки); NF — число полей. awk идеален для CSV/TSV, анализа логов и отчётов — гораздо мощнее cut.
# print columns (default separator: whitespace)
awk '{print $1}' file.txt # first column
awk '{print $1, $3}' file.txt # columns 1 and 3
awk '{print $NF}' file.txt # last column
awk -F: '{print $1}' /etc/passwd # split on :
# filter and print
awk '$3 > 100' file.txt # col 3 > 100
awk '$1 == "ERROR" {print $2}' log # col 2 of ERROR lines
awk 'NR == 5' file.txt # 5th line only
awk 'NR >= 10 && NR <= 20' file.txt # lines 10-20
# BEGIN and END blocks (sum, average)
awk '{sum += $1} END {print sum}' nums.txt
awk '{sum += $2; count++} END {print sum/count}' data.txt
# field separator and output
awk -F, 'BEGIN {OFS="|"} {print $1, $2}' csv.txt
# count lines matching pattern
awk '/error/ {count++} END {print count}' log
# built-in variables: NR (row), NF (fields), FS, OFS
awk '{print NR, NF, $0}' file.txtcut и paste
cut извлекает поля (-f с разделителем -d) или позиции символов (-c). Быстр, но ограничен: не понимает кавычки, поэтому CSV с запятыми в кавычках ломает его. paste объединяет файлы рядом. join соединяет файлы по общему отсортированному полю (как SQL JOIN). expand/unexpand конвертируют табы и пробелы. Для сложной обработки CSV используйте awk или специализированный csvkit.
# cut: extract fields by delimiter
cut -d: -f1 /etc/passwd # field 1, delimiter :
cut -d, -f2,3 data.csv # fields 2 and 3
# cut: extract character positions
cut -c1-5 file.txt # characters 1-5
cut -c1- file.txt # from char 1 to end
# cut: extract bytes (for multibyte)
cut -b1-10 file.txt
# paste: merge files line by line
paste file1.txt file2.txt # tab-separated
paste -d',' file1.txt file2.txt # comma-separated
# paste: serial (all lines of file1, then file2)
paste -s file1.txt # lines into one line
paste -s -d',' file1.txt file2.txt
# join: combine on a common field
join -t, -1 1 -2 1 file1.csv file2.csv
# expand/unexpand tabs
expand file.txt # tabs to spaces
unexpand -a file.txt # spaces to tabssort и uniq
sort упорядочивает строки (-n численно, -r в обратном порядке, -h читаемые размеры, -k поле, -t разделитель). uniq удаляет только СОСЕДНИЕ дубликаты — всегда сначала передавайте через sort. uniq -c считает; sort -rn даёт рейтинг частот. comm сравнивает два ОТСОРТИРОВАННЫХ файла: -12 показывает общие, -23 — только в первом, -13 — только во втором. Паттерн sort | uniq -c | sort -rn — классический анализ частот.
# sort lines
sort file.txt # alphabetical
sort -n nums.txt # numeric
sort -rn nums.txt # reverse numeric
sort -h sizes.txt # human-readable (1K, 2M, 3G)
sort -R file.txt # random order
sort -u file.txt # sort + unique
# sort by field
sort -t: -k3 -n /etc/passwd # by 3rd field, numeric
sort -t, -k2 data.csv # by 2nd field
# sort by multiple keys
sort -k1,1 -k2n file.txt # key1 alpha, key2 numeric
# uniq: filter adjacent duplicates
sort file.txt | uniq # unique lines
sort file.txt | uniq -c # count occurrences
sort file.txt | uniq -d # only duplicates
sort file.txt | uniq -u # only unique lines
# top 10 most frequent lines
sort file.txt | uniq -c | sort -rn | head -10
# compare two sorted files
comm -12 <(sort a.txt) <(sort b.txt) # common lines
comm -23 <(sort a.txt) <(sort b.txt) # only in a
comm -13 <(sort a.txt) <(sort b.txt) # only in btr — замена символов
tr заменяет или удаляет символы (не regex — только наборы символов). -d удаляет, -s сжимает повторы, -c дополняет (инвертирует набор). Идеален для смены регистра, разделителей и очистки данных. tr ',' '\n' превращает CSV в одно значение на строку. tr -cd '0-9' оставляет только цифры. Учтите: tr работает с символами, а не строками, поэтому не заменяет многосимвольные шаблоны — для этого sed.
# translate characters
echo "Hello" | tr 'a-z' 'A-Z' # HELLO (uppercase)
echo "Hello" | tr 'A-Z' 'a-z' # hello (lowercase)
# swap characters
echo "abc" | tr 'abc' 'bca' # bca
# delete characters
echo "hello" | tr -d 'l' # heo
echo "Hello World" | tr -d ' ' # HelloWorld
# squeeze repeated characters
echo "aaabbbccc" | tr -s 'abc' # abc
tr -s ' ' < file.txt # squeeze repeated spaces
# complement (delete everything except)
echo "Hello123" | tr -cd '0-9' # 123 (keep digits only)
echo "Hello123" | tr -cd 'A-Za-z' # Hello
# convert delimiter
echo "a,b,c" | tr ',' '\n' # a\nb\nc (one per line)
echo "a,b,c" | tr ',' '\t' # tab-separated
# ROT13 cipher
echo "Hello" | tr 'A-Za-z' 'N-ZA-Mn-za-m'
# remove non-printable characters
tr -cd '\11\12\15\40-\176' < file.txttee и column
tee раздваивает вывод в файл и stdout — необходимо для логирования внутри конвейеров. sudo tee пишет в файлы, требующие root, не запуская весь конвейер от root. column -t выравнивает текст в аккуратные колонки (отлично для показа CSV). -s задаёт разделитель входа, -o — выхода. fmt и fold переформатируют текст: fmt объединяет абзацы, fold жёстко переносит по ширине.
# tee: write to file AND stdout
echo "hello" | tee file.txt
echo "hello" | tee -a file.txt # append
# tee to multiple files
echo "data" | tee f1.txt f2.txt f3.txt
# tee in a pipeline (log while transforming)
ls -la | tee output.txt | grep ".py"
# tee with sudo (write to privileged file)
echo "config" | sudo tee /etc/myapp.conf
# column: format as aligned columns
column -t file.txt
echo -e "a b c\n1 2 3" | column -t
# column with custom delimiter
column -t -s, data.csv
column -t -s: /etc/passwd
# column with specific separator for output
column -t -o " | " file.txt
# fmt: reformat paragraph width
fmt -w 60 file.txt
# fold: wrap lines at width
fold -w 80 file.txt
fold -w 80 -s file.txt # break at spaces onlyПрава и владение
Просмотр прав
Права — три триплета: владелец, группа, остальные. Каждая позиция r(4), w(2), x(1). Значит, 755 = rwxr-xr-x, 644 = rw-r--r--. Для каталогов x означает «можно войти» (cd), r — «можно перечислить», w — «можно создавать и удалять файлы». stat -c '%a' показывает восьмеричные права. Первый символ ls -l — тип файла (- файл, d каталог, l symlink, b блочное, c символьное).
# view file permissions
ls -l file.txt
# -rw-r--r-- 1 user group 1024 Jan 1 10:00 file.txt
# ^^^ ^^^ ^^^
# owner group others
# rwx r-x r-x = 755
# permission breakdown:
# - = regular file, d = directory, l = symlink
# r = read (4), w = write (2), x = execute (1)
# view all files in directory
ls -la
# view permissions recursively
ls -lR /var/www
# view in octal format
stat -c '%a %n' file.txt # 644 file.txt
stat -c '%a %n' *
# check current umask
umask # e.g., 0022
# directory permissions:
# r = list contents
# w = create/delete files
# x = access (cd into) directorychmod — числовой режим
Восьмеричная запись: каждая цифра — владелец, группа, остальные. r=4, w=2, x=1 — сложите. 755 (rwxr-xr-x) для каталогов и исполняемых файлов; 644 (rw-r--r--) для обычных файлов; 600 (rw-------) для приватных. Для веб-серверов стандарт: каталоги 755, файлы 644. Рекурсивный паттерн на основе find задаёт разные права каталогам и файлам — chmod -R так не умеет.
# numeric (octal) notation
chmod 755 script.sh # rwxr-xr-x
chmod 644 file.txt # rw-r--r--
chmod 600 secrets.txt # rw------- (private)
chmod 777 publicdir/ # rwxrwxrwx (DANGEROUS)
chmod 700 ~/.ssh # rwx------ (for SSH)
# common patterns
chmod 755 directory/ # dirs: owner full, others read+execute
chmod 644 file.txt # files: owner read+write, others read
chmod 600 config.env # sensitive files: owner only
chmod 666 shared.txt # everyone read+write (no execute)
chmod 444 readonly.txt # everyone read only
# recursive
chmod -R 755 project/
chmod -R 644 *.txt # won't work; use find
# recursive: dirs 755, files 644 (common web server setup)
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
# permission reference:
# 7=rwx 6=rw 5=rx 4=r 3=wx 2=w 1=x 0=nonechmod — символьный режим
Символьная запись читаемее для точечных изменений: u/g/o/a (кто), +/-/= (действие), r/w/x/X (что). X (заглавная) ставит выполнение только каталогам или файлам, у которых оно уже есть, — идеально для рекурсивного chmod. --reference копирует права с другого файла. Sticky bit (+t) на каталоге позволяет удалять файлы только их владельцам (используется в /tmp).
# symbolic notation
chmod u+x script.sh # add execute for user
chmod g-w file.txt # remove write for group
chmod o+r file.txt # add read for others
chmod a+x script.sh # add execute for all (a=all)
# combined changes
chmod u+x,g-w,o=r file.txt # user +x, group -w, others = read only
chmod ug+x file.txt # add execute for user and group
chmod a=r file.txt # set everyone to read only
# copy permissions from reference
chmod --reference=template.txt file.txt
# recursive
chmod -R u+rwX,go+rX . # X = execute only for dirs/executables
# symbolic targets:
# u = user (owner)
# g = group
# o = others
# a = all (default)
# operators: + (add), - (remove), = (set exactly)
# permissions: r, w, x, X (execute if dir or already exec), s (SUID/SGID), t (sticky)
# set sticky bit on directory
chmod +t /tmp/shared
chmod 1777 /tmp/sharedchown и chgrp
chown меняет владельца (нужен root или sudo). Формат: owner:group — опустите группу, чтобы менять только владельца; опустите владельца (с двоеточием), чтобы менять только группу. -R рекурсивно входит в каталоги. chgrp — сокращение для chown :group. --from меняет, только если текущий владелец совпадает (условно). Для веб-серверов стандарт — chown -R www-data:www-data. С symlink всегда используйте -h, чтобы менять ссылку, а не цель.
# change owner
chown alice file.txt
chown alice file1.txt file2.txt
# change owner and group
chown alice:developers file.txt
chown alice:developers project/
# recursive
chown -R alice:developers project/
# change group only
chgrp developers file.txt
chown :developers file.txt # alternative
# verbose
chown -v alice file.txt
# reference (copy ownership from another file)
chown --reference=reference.txt file.txt
# change ownership only if currently owned by specific user
chown --from=bob alice file.txt
# symbolic links (by default, changes the link target)
chown -h alice symlink # change the link itself
# common patterns
chown -R www-data:www-data /var/www
chown root:root /etc/sudoers
# view ownership
ls -l file.txt # shows owner and group
stat -c '%U:%G' file.txt # just owner:groupumask
umask задаёт права по умолчанию для новых файлов и каталогов. Это маска: биты вычитаются из значений по умолчанию (666 для файлов, 777 для каталогов). Частые значения: 022 (стандарт, файлы 644, каталоги 755), 077 (приватно, файлы 600, каталоги 700), 002 (совместно с группой, файлы 664, каталоги 775). Задавайте в ~/.bashrc или /etc/profile для постоянства. Учтите: umask не может ДОБАВИТЬ права, только убрать.
# view current umask
umask # e.g., 0022
umask -S # symbolic: u=rwx,g=rx,o=rx
# set umask
umask 022 # new files: 644, dirs: 755
umask 077 # new files: 600, dirs: 700 (private)
umask 002 # new files: 664, dirs: 775 (group-writable)
# how umask works:
# default file perms: 666 (rw-rw-rw-)
# default dir perms: 777 (rwxrwxrwx)
# umask is SUBTRACTED (mask removed)
# umask 022: file = 666-022 = 644, dir = 777-022 = 755
# umask 077: file = 666-077 = 600, dir = 777-077 = 700
# set permanently: add to ~/.bashrc
echo 'umask 022' >> ~/.bashrc
# for security-sensitive environments
umask 077 # only owner can access new files
# for shared group work
umask 002 # group members can write new files
# umask does not affect execute bit on files
# (files are created without execute by default)Специальные права (SUID, SGID, sticky)
SUID (4xxx): программа выполняется с правами владельца файла — это нужно passwd, чтобы менять /etc/shadow от root. SGID (2xxx): у исполняемых файлов — права группы; у каталогов новые файлы наследуют группу каталога (удобно для общих проектов). Sticky bit (1xxx): в каталогах удалять файлы может только владелец файла (или каталога/root) — используется в /tmp. Регулярно проверяйте SUID/SGID файлы: это векторы повышения привилегий.