Primeiros passos
Comandos básicos de arquivo
ls -la mostra os arquivos, incluindo os ocultos. cd ~ vai para o home, cd - alterna para o diretório anterior. mkdir -p cria diretórios pais conforme necessário. rm -r é necessário para diretórios não vazios.
# 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 recursivelyObtendo ajuda
man é o sistema de documentação principal. Seções: 1=comandos, 2=syscalls, 3=biblioteca, 4=dispositivos, 5=formatos de arquivo, 8=administração. man -k (ou apropos) busca nas descrições. --help dá um resumo conciso. tldr fornece exemplos práticos e é instalado separadamente (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 python3Histórico de comandos e atalhos
!! repete o último comando (sudo !! é a correção clássica do 'esqueci o sudo'). !N roda o comando N do histórico. !$ é o último argumento. Ctrl+R é a busca reversa interativa — aperte de novo para achar correspondências anteriores. O histórico fica em ~/.bash_history; HISTSIZE controla o tamanho em memória, HISTFILESIZE o do arquivo.
# 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 fileTipos e identificação de arquivos
file inspeciona os magic bytes de um arquivo para determinar seu tipo real — bem mais confiável que a extensão. ls -F anexa indicadores de tipo (* executável, / diretório, @ symlink, = socket). stat mostra metadados completos do inode, incluindo os três timestamps: Access (atime), Modify (mtime, conteúdo), Change (ctime, metadados).
# 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 timesAtalhos de navegação no terminal
Esses atalhos do Readline funcionam no bash e na maioria dos shells. Ctrl+A/E saltam para o início/fim da linha. Ctrl+W/U/K apagam texto — Ctrl+Y cola de volta (kill ring). Ctrl+R busca no histórico. Ctrl+L limpa a tela. Ctrl+S congela a saída (causa comum de 'terminal congelado' — Ctrl+Q retoma). Aprenda-os para acelerar dramaticamente a edição de linha de comando.
# 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 backwardVariáveis de ambiente
Variáveis de ambiente são herdadas por processos filhos quando exportadas. $PATH determina onde o shell procura comandos — diretórios são buscados em ordem, separados por dois-pontos. ~/.bashrc é carregado em shells interativos não-login; ~/.profile ou ~/.bash_profile em shells de login. Sempre rode source no arquivo depois de editar para aplicar as mudanças. Use printenv VAR para verificar uma variável única sem expansão.
# 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 ~/.bashrcOperações de arquivo
Copiando arquivos (cp)
cp copia arquivos. -r (ou -R) é necessário para diretórios. -i pergunta antes de sobrescrever (recomendado para evitar perda de dados). -p preserva metadados; -a é modo archive (preserva tudo, incluindo symlinks — ideal para backups). -u só atualiza se a fonte for mais nova. Sempre use -i em scripts em que sobrescrever é arriscado.
# 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/Mover e renomear (mv)
mv é tanto mover quanto renomear — atualiza a entrada de diretório sem copiar dados (instantâneo no mesmo filesystem). -i pergunta antes de sobrescrever. mv -n impede sobrescrever arquivos existentes. O comando rename (baseado em Perl no Debian/Ubuntu) usa regex para renomear em lote — muito mais poderoso que loops com mv. Nota: a sintaxe do rename difere entre distribuições (versão util-linux vs 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 *.JPGRemovendo arquivos (rm)
rm exclui arquivos permanentemente (sem lixeira). -r é necessário para diretórios. -rf é perigoso — exclui recursivamente sem perguntar; sempre confira o path duas vezes. Nunca rode rm -rf / ou rm -rf $VAR/ quando $VAR pode estar vazio. Considere trash-cli para exclusão recuperável. find -delete é mais seguro para exclusão por padrão, porque você pode testar sem -delete primeiro.
# 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-restoreCriando arquivos (touch)
touch cria arquivos vazios ou atualiza os timestamps de arquivos existentes. Sem opções, define tanto atime quanto mtime como o tempo atual. -t define um timestamp específico. -r copia o timestamp de um arquivo de referência. Para criar um arquivo com conteúdo, use redirecionamento (>) ou um here-document. touch é comumente usado para criar arquivos placeholder ou forçar o make a reconstruir alvos.
# 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
EOFHard links e symlinks (ln)
Hard links compartilham o mesmo inode (dados) — excluir um não apaga os dados até que o último link seja removido. Não atravessam filesystems nem linkam a diretórios. Symlinks são referências de path — quebram se o alvo se mover ou for excluído, mas podem linkar entre filesystems e a diretórios. Use ln -s para symlinks (o mais comum). readlink -f resolve toda a cadeia até o arquivo real.
# 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_nameMetadados de arquivo (stat, basename, dirname)
stat mostra metadados completos do inode. basename e dirname decompõem paths — essenciais em scripts que processam listas de arquivos. realpath resolve paths relativos e symlinks em paths absolutos canônicos. stat -c permite formatos de saída personalizados (%n=nome, %s=tamanho, %y=mtime, %a=permissões octais) — útil em scripts. Essas ferramentas substituem expansão de parâmetros frágil para manipulação de paths.
# 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-readableOperações de diretório
Criando diretórios (mkdir)
mkdir -p cria diretórios pais conforme necessário e não dá erro se o diretório já existir — essencial para scripts idempotentes. -m define permissões diretamente (sobrescreve o umask). Brace expansion ({a,b,c}) combinada com mkdir -p cria árvores de diretórios complexas num único comando. É um padrão comum para montar estruturas de projeto.
# 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}Removendo diretórios (rmdir, rm)
rmdir só remove diretórios vazios — seguro, mas limitado. rm -r remove diretórios não vazios recursivamente. rm -rf é a opção nuclear: sempre verifique o path primeiro. O padrão find -empty -delete remove apenas diretórios vazios sem tocar nos povoados. Em scripts, sempre verifique que a variável não está vazia antes de rm -rf para não excluir / acidentalmente.
# 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/Listagem e árvore de diretórios
ls -d */ lista só diretórios. tree fornece uma hierarquia visual — -L limita a profundidade, -I exclui padrões (incredivelmente útil para excluir node_modules/.git). Para árvores de diretórios grandes, combine tree -d -L 2 para uma visão rápida. ls -1 (é o número um) lista um arquivo por linha — útil para pipe em wc -l para contar.
# 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 -lTamanho de diretórios (du)
du mede o uso de disco. -s (summary) mostra só o total, -h o torna legível para humanos. du -sh */ dá os tamanhos dos subdiretórios imediatos. sort -rh ordena por tamanho legível em ordem reversa (maiores primeiro). --exclude pula padrões. A diferença entre apparent-size e o padrão: apparent mostra o tamanho lógico do arquivo, o padrão mostra os blocos de disco realmente alocados (que podem ser maiores por causa do tamanho do bloco).
# 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 .Pilha de diretórios (pushd, popd)
pushd/popd gerenciam uma pilha de diretórios — pushd salva o diretório atual e navega a um novo; popd volta ao salvo. dirs mostra a pilha. É mais poderoso que cd - (que só alterna entre dois diretórios). Útil em scripts que precisam navegar entre vários diretórios e voltar. A sintaxe +N rotaciona ou remove por posição.
# 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 directoryVisualização de arquivos
cat e tac
cat despeja o arquivo inteiro no stdout — ok para arquivos pequenos, mas use less/head para os grandes. cat -n numera linhas. cat -A revela caracteres ocultos (tabulações, finais de linha) — útil para depurar problemas de formatação. tac inverte a ordem das linhas (cat ao contrário). cat também serve para concatenar arquivos e redirecionar entrada. Para ver arquivos grandes interativamente, use 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 endPager less
less é o pager padrão — muito melhor que more, porque permite navegação para trás. Os keybindings lembram o vim (j/k/g/G). / busca para frente, ? para trás. F entra no 'modo follow' (como tail -f) para observar logs. O less trata arquivos comprimidos automaticamente se lesspipe estiver configurado. Aperte v para abrir o arquivo atual no seu $EDITOR para edições rápidas.
# 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 e tail
head mostra o início, tail mostra o fim de um arquivo. tail -f é essencial para monitorar arquivos de log em tempo real. tail -F (maiúsculo) lida com rotação de arquivos (quando logs são renomeados/truncados) reabrindo o arquivo. head -n -N mostra tudo, exceto as últimas N linhas. Para arquivos grandes, head/tail são instantâneos (não leem o arquivo inteiro).
# 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.txtVendo linhas específicas
sed -n 'Np' imprime números de linha específicos. awk com NR (número do registro) é mais flexível para faixas e condições. O truque (head; tail) mostra as duas pontas de um arquivo grande. nl e cat -n numeram linhas. hexdump/xxd exibem arquivos binários em hex — essencial para inspecionar arquivos não textuais, depurar formatos de arquivo ou recuperar dados.
# 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.binContagem de palavras e linhas (wc)
wc (word count) reporta linhas (-l), palavras (-w), bytes (-c), caracteres (-m, respeita a codificação) e o comprimento da maior linha (-L). Com múltiplos arquivos, mostra contagens por arquivo e um total. O padrão grep | wc -l conta linhas correspondentes — mas grep -c é mais eficiente (sem pipe). Para contar arquivos, ls -1 | wc -l é rápido, mas find é mais preciso para contagens recursivas.
# 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 -lBusca de arquivos
find por nome e tipo
find é a ferramenta de busca de arquivos mais poderosa. -name casa nomes de arquivos com padrões glob; -iname ignora maiúsculas. -type filtra por tipo de arquivo (f=arquivo, d=diretório, l=symlink). -maxdepth limita a recursão (importante para desempenho). -not e -prune excluem paths. \( -name A -o -name B \) agrupa condições com OU. Sempre coloque padrões entre aspas para impedir expansão glob do shell.
# 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 por tempo e tamanho
Busca por tempo: -mtime (dias), -mmin (minutos). - (menor que) e + (maior que) prefixam o valor. -atime é o tempo de acesso, -ctime o tempo de mudança de metadados. Sufixos de tamanho: c (bytes), k (KB), M (MB), G (GB). -perm 644 casa exatamente; -perm -u+x casa arquivos com bit de execução para o usuário; /4000 casa qualquer arquivo SUID. Encontrar arquivos SUID é uma técnica de auditoria de segurança.
# 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 e -delete
-exec roda um comando sobre cada resultado. {} é o placeholder do nome do arquivo; \; roda o comando uma vez por arquivo; + agrupa arquivos (mais eficiente, menos processos). -delete é mais seguro que -exec rm porque é atômico. Sempre teste com -print antes de adicionar -delete. -ok pede confirmação por arquivo. O padrão dirs-755-files-644 é a configuração padrão de permissões de servidores web.
# 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 e which
locate busca num banco de dados pré-construído (atualizado pelo updatedb, geralmente via cron) — muito mais rápido que find, mas pode estar desatualizado. Rode sudo updatedb para atualizar. which encontra executáveis no $PATH. whereis também acha código-fonte e man pages. type mostra como o shell resolve um comando (alias, builtin ou arquivo) — mais preciso que which para builtins do shell. command -v é a forma portável 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 python3Receitas práticas de find
Essas receitas mostram o poder real do find. -printf permite formatação de saída personalizada (%s=tamanho, %p=path). -newermt casa pelo tempo de modificação com strings de data. -newer compara com um arquivo de referência. O buscador de symlinks quebrados usa test -e dentro de -exec. A receita de contagem de arquivos por extensão é um pipeline clássico combinando find, sed, sort e uniq para analisar uma base de código rapidamente.
# 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 -rnBusca de texto (grep)
Padrões grep básicos
grep acha linhas que casam com um padrão. -i ignora maiúsculas, -w casa palavras inteiras, -v inverte, -c conta, -n numera linhas, -l lista nomes de arquivos, -h suprime nomes de arquivos, -o mostra só a correspondência. Por padrão, o grep usa Regex Básica (BRE); use -E para Regex Estendida (sintaxe mais limpa) ou -F para strings fixas (mais rápido, sem 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 com expressões regulares
grep -E (ou egrep) usa Expressões Regulares Estendidas, em que +, ?, |, () funcionam sem barras invertidas. ^ e $ ancoram no início/fim da linha. [] define classes de caracteres; {} especifica repetição. -P habilita Regex Compatível com Perl (PCRE) com \d, \w, \b, lookarounds — poderoso, mas específico do GNU. -F trata o padrão como string fixa (sem interpretação de regex), mais rápido para buscas literais.
# 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.txtContexto e saída do grep
Flags de contexto (-B, -A, -C) mostram linhas ao redor — essenciais para entender entradas de log. --color destaca as correspondências. -r busca recursivamente (exclui symlinks); -R segue symlinks. --include/--exclude/--exclude-dir filtram quais arquivos buscar — sempre exclua node_modules e .git. -a força arquivos binários a serem tratados como texto; -I os pula. -rn combina recursão com números de linha.
# 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 em pipelines
O truque [n]ginx impede que o grep case com o próprio processo dele: os colchetes fazem o padrão não casar com a string literal 'grep' na lista de processos. zgrep busca em arquivos comprimidos. pgrep é um buscador de processos especializado. grep -rl lista arquivos contendo um padrão; fazer pipe para xargs grep busca nesses arquivos por outro padrão — uma técnica comum de arqueologia de código.
# 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 -20Status de saída do grep e scriptação
O status de saída do grep o torna ideal para scripts: 0 (correspondência encontrada), 1 (nenhuma), 2 (erro). -q (quiet) suprime a saída para checagens puramente condicionais. Em scripts com set -e, grep retornando 1 (nenhuma correspondência) encerraria o script — use '|| true' para prevenir. grep -c retorna uma contagem. Essa capacidade de script faz do grep um bloco construtor para monitoramento de logs, validação e checagens de 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) — alternativa moderna
ripgrep (rg) é uma alternativa moderna e rápida ao grep para busca de código. É recursivo por padrão, respeita .gitignore e é significativamente mais rápido. -t/-T filtram por tipo de arquivo (definições de tipo embutidas). -g usa padrões glob. Diferente do grep, o rg pula arquivos ocultos e ignorados pelo git por padrão — use --hidden e --no-ignore para sobrescrever. Instale com: cargo install ripgrep ou 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 newlinesProcessamento de texto
sed — editor de stream
sed edita streams de texto de forma não interativa. s substitui (g para global); d exclui; p imprime. -i edita no lugar (sempre teste sem -i primeiro, ou use -i.bak para um backup). O delimitador pode ser qualquer caractere — use | ou # para paths, evitando escapar barras. -E habilita regex estendida com sintaxe de grupos de captura mais limpa. O sed processa linha por linha.
# 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 — processamento de colunas
awk é uma mini linguagem de programação para dados colunares. $1, $2... são campos; $0 é a linha inteira; $NF é o último campo. -F define o separador de entrada; OFS define o de saída. BEGIN roda antes do processamento, END depois. NR é o número do registro (linha); NF é a contagem de campos. awk é ideal para processar CSV/TSV, analisar logs e relatórios — muito mais poderoso que 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 e paste
cut extrai campos (-f com delimitador -d) ou posições de caracteres (-c). É rápido, mas limitado — sem suporte a aspas, então CSVs com vírgulas entre aspas o quebram. paste mescla arquivos lado a lado. join combina arquivos por um campo comum ordenado (como um SQL JOIN). expand/unexpand convertem entre tabs e espaços. Para processamento complexo de CSV, use awk ou uma ferramenta dedicada como 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 e uniq
sort ordena linhas (-n numérico, -r reverso, -h legível para humanos, -k campo, -t delimitador). uniq só remove duplicatas ADJACENTES — sempre faça pipe pelo sort primeiro. uniq -c conta; sort -rn dá um ranking de frequência. comm compara dois arquivos ORDENADOS: -12 mostra os comuns, -23 só no primeiro, -13 só no segundo. O padrão sort | uniq -c | sort -rn é o pipeline clássico de análise de frequência.
# 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 — traduzir caracteres
tr traduz ou exclui caracteres (não regex — apenas conjuntos de caracteres). -d exclui, -s comprime repetições, -c complementa (inverte o conjunto). Perfeito para conversão de caixa, troca de delimitadores e limpeza de dados. tr ',' '\n' converte CSV para um valor por linha. tr -cd '0-9' extrai só dígitos. Nota: tr trabalha com caracteres, não strings, então não consegue substituir padrões de múltiplos caracteres — use sed para isso.
# 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 e column
tee divide a saída entre um arquivo e o stdout — essencial para logar dentro de pipelines. sudo tee escreve em arquivos que exigem root sem rodar o pipeline inteiro como root. column -t alinha o texto em colunas organizadas (ótimo para exibir CSVs). -s especifica o delimitador de entrada, -o o separador de saída. fmt e fold reorganizam texto — fmt junta parágrafos, fold quebra em uma largura fixa.
# 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 onlyPermissões e propriedade
Vendo permissões
As permissões são três tercetos: owner, group, others. Cada posição é r(4), w(2), x(1). Então 755 = rwxr-xr-x, 644 = rw-r--r--. Para diretórios, x significa 'pode acessar' (cd para dentro), r significa 'pode listar', w significa 'pode criar/excluir arquivos'. stat -c '%a' mostra as permissões octais. O primeiro caractere de ls -l é o tipo de arquivo (- arquivo, d diretório, l symlink, b bloco, c caractere).
# 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 — modo numérico
Notação numérica (octal): cada dígito representa owner, group, others. r=4, w=2, x=1 — some-os. 755 (rwxr-xr-x) para diretórios e executáveis; 644 (rw-r--r--) para arquivos regulares; 600 (rw-------) para arquivos privados. Para servidores web, o padrão é dirs=755, files=644. O padrão recursivo baseado em find aplica permissões diferentes a dirs e arquivos — chmod -R não consegue fazer isso.
# 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 — modo simbólico
A notação simbólica é mais legível para mudanças incrementais: u/g/o/a (quem), +/-/= (ação), r/w/x/X (o quê). X (maiúsculo) define execução apenas para diretórios ou arquivos que já têm execução — perfeito para chmod recursivo. --reference copia permissões de outro arquivo. O sticky bit (+t) num diretório significa que só os donos dos arquivos podem excluí-los (usado em /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 e chgrp
chown muda a propriedade (exige root ou sudo). Formato: owner:group — omita o grupo para mudar só o owner, omita o owner (com dois-pontos) para mudar só o grupo. -R recursa em diretórios. chgrp é um atalho para chown :group. --from só muda se o owner atual corresponder (condicional). Para servidores web, chown -R www-data:www-data é o padrão. Sempre use -h com symlinks para mudar o link, não o alvo.
# 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 define as permissões padrão para arquivos e diretórios recém-criados. É uma máscara — bits são removidos do padrão (666 para arquivos, 777 para dirs). Valores comuns: 022 (padrão, arquivos 644/dirs 755), 077 (privado, arquivos 600/dirs 700), 002 (compartilhado por grupo, arquivos 664/dirs 775). Defina-o em ~/.bashrc ou /etc/profile para persistência. Nota: umask não pode ADICIONAR permissões, só removê-las.
# 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)Permissões especiais (SUID, SGID, Sticky)
SUID (4xxx): o programa roda com os privilégios do dono do arquivo — passwd precisa disso para modificar /etc/shadow como root. SGID (2xxx): em executáveis, roda com privilégios do grupo; em diretórios, arquivos novos herdam o grupo do diretório (útil para projetos compartilhados). Sticky bit (1xxx): em diretórios, só o dono do arquivo (ou dono do dir/root) pode excluí-lo — usado em /tmp. Audite arquivos SUID/SGID regularmente, pois são vetores de escalada de privilégio.
# SUID (Set User ID): runs as file owner
chmod u+s /usr/bin/passwd # 4755 -> rwsr-xr-x
chmod 4755 myprogram
# SGID (Set Group ID): runs as group owner
chmod g+s /shared/dir # dirs: new files inherit group
chmod 2755 /shared/project
# Sticky bit: only file owner can delete
chmod +t /tmp # 1777 -> rwxrwxrwt
chmod 1777 /shared/upload
# view special permissions
ls -l /usr/bin/sudo
# -rwsr-xr-x (s in user position = SUID)
ls -ld /tmp
# drwxrwxrwt (t in others position = sticky)
# find SUID files (security audit)
find / -perm -4000 -type f 2>/dev/null
# find SGID files
find / -perm -2000 -type f 2>/dev/null
# find sticky directories
find / -perm -1000 -type d 2>/dev/null
# numeric special bits:
# 1 = sticky, 2 = SGID, 4 = SUID
# chmod 4755 = SUID + 755
# chmod 2755 = SGID + 755
# chmod 1777 = sticky + 777
# uppercase S/T means execute bit is NOT set (usually an error)
# rws = SUID + execute, rwS = SUID without executeUsuários e grupos
Gerenciamento de usuários
useradd cria usuários (baixo nível; adduser é um wrapper mais amigável no Debian). -m cria o diretório home; -s define o shell; -c define o nome completo; -G adiciona a grupos suplementares. usermod -aG acrescenta a grupos sem remover os existentes (sempre use -a com -G). userdel -r remove o diretório home. passwd define senhas. /etc/passwd guarda informações de usuários; /etc/shadow guarda os hashes de senha.
# add a new user
sudo useradd -m -s /bin/bash alice
# -m: create home directory
# -s: specify login shell
# add user with full options
sudo useradd -m -s /bin/bash -c "Alice Smith" -G sudo,docker alice
# set password
sudo passwd alice
# delete a user
sudo userdel alice
sudo userdel -r alice # remove home directory too
# modify user
sudo usermod -aG docker alice # append to group (-a = append)
sudo usermod -s /bin/zsh alice # change shell
sudo usermod -L alice # lock account
sudo usermod -U alice # unlock account
sudo usermod -l newname oldname # rename user
# view user info
id alice # uid, gid, groups
finger alice # detailed info (if installed)
# change login shell
chsh -s /bin/zsh
# list all users
cat /etc/passwd | cut -d: -f1
getent passwd | cut -d: -f1Gerenciamento de grupos
Grupos organizam usuários para acesso compartilhado. groupadd/groupdel/groupmod gerenciam grupos. usermod -aG (acrescentar ao grupo) é a forma padrão de adicionar um usuário — sem -a, você substituiria o conjunto inteiro de grupos suplementares dele. gpasswd é uma ferramenta alternativa. /etc/group guarda as definições de grupos. newgrp inicia um novo shell com um grupo primário diferente (útil ao criar arquivos que devem pertencer ao grupo).
# create a group
sudo groupadd developers
# create group with specific GID
sudo groupadd -g 2000 developers
# delete a group
sudo groupdel developers
# modify group
sudo groupmod -n devs developers # rename
sudo groupmod -g 2001 developers # change GID
# add user to group
sudo usermod -aG docker alice # append to group
sudo gpasswd -a alice developers # alternative
# remove user from group
sudo gpasswd -d alice developers
sudo deluser alice developers # Debian/Ubuntu
# list groups
cat /etc/group | cut -d: -f1
getent group
# view groups for a user
groups alice
id alice
# set group administrator
sudo gpasswd -A alice developers
# temporarily switch primary group
newgrp developers # new shell with group as primary
# view group members
getent group developers # lists members
grep developers /etc/groupGerenciamento de senhas
passwd muda senhas. -l bloqueia uma conta (adiciona ! ao hash); -u desbloqueia. -e força uma mudança de senha no próximo login. chage gerencia políticas de envelhecimento de senha: -M (máximo de dias), -m (mínimo de dias), -W (dias de aviso), -E (data de expiração). Hashes de senha ficam em /etc/shadow (legível só por root), não em /etc/passwd. Uma boa política de senhas exige mudanças regulares com requisitos de complexidade.
# change your own password
passwd
# change another user's password (requires root)
sudo passwd alice
# set password interactively
sudo passwd alice
# Enter new password: ******
# Retype new password: ******
# lock/unlock a password
sudo passwd -l alice # lock (prepends !)
sudo passwd -u alice # unlock
# force password change on next login
sudo passwd -e alice
sudo chage -d 0 alice
# set password aging policy
sudo chage -M 90 alice # max 90 days
sudo chage -m 7 alice # min 7 days between changes
sudo chage -W 7 alice # warn 7 days before expiry
sudo chage -E 2025-12-31 alice # expire on date
# view password aging info
chage -l alice
# password quality: /etc/login.defs
# PASS_MAX_DAYS 90
# PASS_MIN_DAYS 7
# PASS_MIN_LEN 12
# PASS_WARN_AGE 7
# check password hash in /etc/shadow
sudo grep alice /etc/shadowComandos de informação de usuário
whoami mostra seu nome de usuário atual; id mostra uid/gid/grupos. who lista os usuários logados; w adiciona o que estão rodando. last mostra o histórico de logins de /var/log/wtmp; lastb mostra tentativas falhas de /var/log/btmp. getent passwd consulta o banco de usuários (incluindo LDAP, se configurado). Esses comandos são essenciais para administração de sistema e auditoria de atividade de usuários.
# who am I
whoami # current username
id # uid, gid, groups
echo $USER # from environment
# who is logged in
who # all logged-in users
w # detailed (what they're doing)
users # just usernames
# last logins
last # recent logins
last -n 10 # last 10 logins
last alice # alice's logins
last reboot # reboot history
# failed login attempts
lastb # bad login attempts (requires root)
# user account info
finger alice # detailed info (if installed)
getent passwd alice # /etc/passwd entry
# group membership
groups # your groups
groups alice # alice's groups
id alice # uid, gid, all groups
# check if user exists
id alice && echo "exists" || echo "not found"
getent passwd alice
# list all users with home directories
getent passwd | awk -F: '{print $1, $6}'su e sudo
su troca de usuário (precisa da senha do usuário alvo); sudo roda um comando como root (precisa da sua senha). su - inicia um shell de login (carrega o perfil do usuário alvo). sudo é preferido pela auditoria: os comandos são registrados em /var/log/auth.log. visudo edita /etc/sudoers com segurança (valida a sintaxe antes de salvar). Regras NOPASSWD são convenientes, mas reduzem a segurança. sudo !! repete o último comando como root — a correção clássica do 'esqueci o sudo'.
# switch to root
su # needs root password
su - # login shell (loads root's profile)
# switch to another user
su - alice # login as alice
su alice # as alice, keep current env
# run a single command as root
sudo command
sudo apt update
# run a command as another user
sudo -u alice command
sudo -u www-data php script.php
# edit a file as root
sudo vim /etc/fstab
sudoedit /etc/fstab # safer alternative
# sudo with environment
sudo -E command # preserve environment variables
# list sudo privileges
sudo -l # what can I run?
sudo -l -U alice # what can alice run?
# sudo configuration
sudo visudo # edit /etc/sudoers safely
# /etc/sudoers.d/ for individual rules
# alice ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx
# run previous command as root
sudo !! # classic fix for forgetting sudo
# sudo timeout: 5 min by default
sudo -v # extend timeout
sudo -k # kill timeout (require password next time)Gerenciamento de processos
ps — listagem de processos
ps mostra um snapshot dos processos. aux (BSD) e -ef (System V) são os dois estilos comuns. O padrão 'ps aux | grep' é onipresente (use o truque [n]ginx para não casar com o grep). pstree mostra relações pai-filho. --sort=-%mem ordena por uso de memória (acha os devoradores de recursos). Estados-chave: R=rodando, S=dormindo, D=sleep ininterruptível, Z=zumbi, T=parado. Para monitoramento em tempo real, use top ou htop.
# list processes (BSD style)
ps aux # all processes, full format
ps aux | grep nginx # find specific process
# list processes (System V style)
ps -ef # all processes
ps -ef | grep python
# list processes in a tree
ps auxf # forest/tree view
pstree # dedicated tree tool
pstree -p # with PIDs
# show specific user's processes
ps -u alice
# show process by PID
ps -p 1234
ps -p 1234 -o pid,ppid,cmd
# custom output format
ps -eo pid,ppid,user,%mem,%cpu,cmd --sort=-%mem | head
# show threads
ps -eLf | grep java # show threads (LWP)
# ps output columns:
# PID process ID
# PPID parent process ID
# USER owner
# %CPU CPU usage
# %MEM memory usage
# VSZ virtual memory size (KB)
# RSS resident set size (KB)
# STAT process state (R=running, S=sleeping, Z=zombie)
# START start time
# TIME CPU time
# CMD commandtop e htop
top é o monitor de processos em tempo real embutido. Comandos-chave: M (ordenar por memória), P (ordenar por CPU), k (matar), q (sair). O modo -b (batch) gera texto para scripts. htop é uma alternativa superior (colorido, rolável, suporte a mouse, visão em árvore) — instale com apt install htop. glances fornece um panorama completo do sistema. Para achar o que está consumindo recursos, top/htop ordenado por %CPU ou %MEM é a ferramenta de escolha.
# real-time process monitor
top
# top interactive commands:
# P sort by CPU usage
# M sort by memory usage
# N sort by PID
# T sort by running time
# k kill a process (enter PID)
# r renice (change priority)
# 1 show per-CPU stats
# u filter by user
# H show threads
# c toggle full command path
# W write settings to ~/.toprc
# q quit
# run top with specific sorting
top -o %MEM # sort by memory
top -o %CPU # sort by CPU
# batch mode (for scripts)
top -b -n 1 # one snapshot
top -b -n 1 | head -20 # top 20 processes
# monitor specific user
top -u alice
# htop: better interactive viewer (install separately)
htop # colorized, mouse support
htop -p 1234 # monitor specific PID
# glance: alternative system monitor
glances # needs installationkill e killall
kill envia sinais por PID; killall/pkill enviam por nome. Sempre tente SIGTERM (padrão) primeiro — permite limpeza graciosa. SIGKILL (-9) é forçado e imediato; o processo não pode capturá-lo, então pode deixar recursos em estado ruim. Use como último recurso. pkill -f casa com a linha de comando inteira. kill -l lista os sinais. O padrão 'kill; sleep; kill -9' dá ao processo uma chance de limpar antes de forçar.
# send signal to a process by PID
kill 12345 # SIGTERM (graceful, default)
kill -15 12345 # SIGTERM explicitly
kill -9 12345 # SIGKILL (force, cannot be caught)
kill -HUP 12345 # SIGHUP (reload config)
# kill by name
killall nginx # kill all nginx processes
pkill -f "python app.py" # match full command line
pkill -u alice # kill all of alice's processes
# common signals
kill -l # list all signals
# SIGTERM (15) - graceful termination (default)
# SIGKILL (9) - force kill (cannot be caught)
# SIGINT (2) - interrupt (Ctrl+C)
# SIGHUP (1) - hangup (often reload config)
# SIGSTOP (19) - pause (cannot be caught)
# SIGCONT (18) - resume
# SIGUSR1/USR2 - user-defined signals
# graceful then forceful
kill 12345; sleep 2; kill -9 12345 2>/dev/null
# kill background job
kill %1 # kill job 1
# find and kill by port
fuser -k 8080/tcp # kill process using port 8080
kill $(lsof -t -i:8080) # alternativeJobs em segundo plano e controle de jobs
Acrescentar & roda em segundo plano. jobs lista jobs ativos; fg/bg movem entre primeiro e segundo plano. Ctrl+Z suspende o job em primeiro plano. wait bloqueia até os jobs em segundo plano terminarem. nohup e disown ambos impedem que o processo morra quando o terminal fecha — nohup para comandos novos, disown para os já rodando. Para trabalho persistente, use tmux ou screen.
# run in background (append &)
sleep 100 &
# [1] 12345 (job 1, PID 12345)
# list jobs
jobs
jobs -l # with PIDs
# bring to foreground / send to background
fg # foreground the current job
fg %1 # foreground job 1
bg %2 # background job 2
# Ctrl+Z: suspend foreground job, then resume in background
# Ctrl+Z sends SIGTSTP
bg # resume in background
# wait for background jobs
wait # wait for all
wait $! # wait for last background job
wait 12345 # wait for specific PID
# disown: detach from shell (survives logout)
long_task &
disown %1
# nohup: run immune to hangups (survives logout)
nohup ./script.sh > output.log 2>&1 &
# run at lower priority
nice -n 10 ./backup.sh &
# parallel execution
cmd1 & cmd2 & cmd3 &
wait # wait for all to finishnice e renice — prioridade de processos
Os valores de nice vão de -20 (prioridade mais alta) a 19 (mais baixa). Usuários comuns só podem baixar a prioridade (valores positivos); root pode aumentá-la (negativos). O padrão é 0. nice inicia um processo com uma prioridade; renice muda um processo em execução. Para tarefas intensivas em I/O, ionice controla a prioridade de I/O de disco (classes: 1=realtime, 2=best-effort, 3=idle). cpulimit limita o uso de CPU — útil para tarefas em segundo plano que não devem interferir.
# nice: start a process with adjusted priority
nice ./script.sh # default: +10 (lower priority)
nice -n 10 ./backup.sh # priority 10 (lower)
nice -n -5 ./critical.sh # higher priority (needs root)
# renice: change priority of running process
renice 5 -p 12345 # PID 12345 to priority 5
renice 10 -u alice # all of alice's processes
renice -5 -p 12345 # higher priority (needs root)
# view priorities
ps -l # NI column shows nice value
top # NI column
# nice values:
# -20 highest priority (most favorable)
# 0 default
# 19 lowest priority (least favorable)
# only root can set negative (higher) priority
# practical: run CPU-intensive task at low priority
nice -n 19 make -j4 &
# ionice: I/O priority
ionice -c 3 ./backup.sh # idle I/O priority
ionice -c 2 -n 7 ./backup.sh # best-effort, low
# cpulimit: limit CPU usage (install separately)
cpulimit -p 12345 -l 50 # limit to 50% CPUFilesystem /proc
/proc é um filesystem virtual (sem armazenamento em disco) que expõe informações do kernel e dos processos. /proc/PID/ contém dados por processo. /proc/cpuinfo, /proc/meminfo mostram hardware. /proc/sys/ contém parâmetros ajustáveis do kernel (equivalente ao sysctl). Escrever em /proc/sys/ muda as configurações do kernel imediatamente (mas use sysctl para persistência). /proc/mounts mostra os filesystems montados no momento. Essa é a interface principal entre o userspace e o kernel.
# /proc: virtual filesystem with kernel/process info
# process info by PID
cat /proc/1234/status # process status
cat /proc/1234/cmdline # command line (null-separated)
ls -l /proc/1234/fd/ # open file descriptors
cat /proc/1234/environ # environment variables (null-separated)
# system info
cat /proc/cpuinfo # CPU information
cat /proc/meminfo # memory information
cat /proc/version # kernel version
cat /proc/uptime # uptime in seconds
cat /proc/loadavg # load average
# network info
cat /proc/net/tcp # TCP connections
cat /proc/net/dev # network interface stats
# kernel settings
ls /proc/sys/ # sysctl parameters
cat /proc/sys/net/ipv4/ip_forward
echo 1 > /proc/sys/net/ipv4/ip_forward # enable IP forwarding
# mount info
cat /proc/mounts # mounted filesystems
cat /proc/filesystems # supported filesystem types
# view process memory maps
cat /proc/1234/maps # memory mappings
pmap 1234 # formatted versionInformações do sistema
uname e hostname
uname mostra informações do kernel (-a para tudo). hostname mostra/define o nome do sistema — hostnamectl set-hostname o torna persistente. /etc/os-release é a forma padrão de identificar a distribuição (funciona em qualquer Linux moderno). lscpu dá informações detalhadas da arquitetura de CPU. dmidecode lê dados de BIOS/SMBIOS. Esses comandos são o primeiro passo de qualquer tarefa de administração para entender com o que você está lidando.
# kernel and system info
uname # kernel name: Linux
uname -a # all info
uname -r # kernel release: 5.15.0-91-generic
uname -m # machine hardware: x86_64
uname -n # network node (hostname)
uname -p # processor type
uname -o # operating system: GNU/Linux
# hostname
hostname # current hostname
hostname -f # fully qualified domain name
hostname -I # all IP addresses
# set hostname (persistent)
sudo hostnamectl set-hostname myserver
# distribution info
cat /etc/os-release # distro name and version
lsb_release -a # Ubuntu/Debian specific
cat /etc/debian_version # Debian version
# kernel version
cat /proc/version
dmesg | grep "Linux version"
# system architecture
arch # e.g., x86_64
dpkg --print-architecture # Debian/Ubuntu
# BIOS/hardware info
sudo dmidecode -t system # system info
sudo dmidecode -t bios # BIOS info
lshw # hardware list
lscpu # CPU detailsdf — espaço livre em disco
df reporta o espaço em disco dos filesystems. -h (legível para humanos) é essencial. -T mostra o tipo de filesystem (ext4, xfs, btrfs, tmpfs, nfs). -i mostra o uso de inodes — você pode ficar sem inodes antes de ficar sem espaço (comum com muitos arquivos pequenos). -x exclui tipos de filesystem (útil para filtrar filesystems virtuais como tmpfs). Quando o disco enche, verifique df -h primeiro, e depois use du para achar os diretórios que consomem espaço.
# show disk space for all filesystems
df # all mounted filesystems
df -h # human-readable (K, M, G)
df -H # SI units (KB, MB, GB)
# specific filesystem
df -h /home # space for /home
df -h /dev/sda1 # specific device
# filesystem type
df -T # show type (ext4, xfs, tmpfs, etc.)
df -Th # human-readable + type
# exclude specific types
df -x tmpfs -x devtmpfs # exclude virtual filesystems
# inodes (file count limit)
df -i # inode usage
df -ih # human-readable inode usage
# local filesystems only
df -l
# show total
df -h --total
# find the filesystem using the most space
df -h | sort -rh -k5 | head
# real-time: watch disk space
watch -n 5 df -hdu — uso de disco
du mede o uso de disco. -s (summary) mostra só os totais; -h é legível para humanos. du -sh */ dá os tamanhos dos subdiretórios imediatos. sort -rh ordena por valores legíveis. --apparent-size mostra o tamanho lógico do arquivo vs os blocos de disco reais. --exclude pula padrões. Para achar o que está consumindo espaço, o fluxo é: df -h (qual filesystem está cheio) → du -sh * (qual diretório) → find (quais arquivos).
# size of current directory
du -sh .
# size of specific directories
du -sh /var/log /tmp /home
# size of all immediate subdirectories
du -sh */
du -sh * | sort -rh # sorted largest first
# top 10 largest directories
du -sh * | sort -rh | head -10
# maximum depth
du -h -d 1 # depth 1 only
du -h --max-depth=2
# include hidden files
du -sh .[!.]*
# apparent size (logical, not disk blocks)
du -sh --apparent-size file
# exclude patterns
du -sh --exclude='*.log' .
du -sh --exclude=node_modules .
# total of multiple directories
du -sh /var/log /var/lib /tmp | tail -1
# find largest files (not just directories)
find / -type f -exec ls -lhS {} + 2>/dev/null | head -10
find . -type f -printf '%s %p\n' | sort -rn | head -10
# sort all subdirectories by size
du -sh ./*/* | sort -rh | head -20free — uso de memória
free mostra o uso de memória. A coluna 'available' é a mais significativa — estima quanta memória está disponível para iniciar novas aplicações sem swap. O Linux usa intencionalmente a RAM livre como cache (buff/cache) para acelerar leituras de disco; isso é recuperado sob demanda, então um 'free' baixo é normal. O uso de swap deve ser monitorado — swap alto com troca ativa (si/so no vmstat) indica pressão de memória.
# show memory usage
free # in KB
free -h # human-readable
free -m # in MB
free -g # in GB
# continuous update
free -h -s 1 # update every 1 second
watch -n 1 free -h # alternative
# output:
# total used free shared buff/cache available
# Mem: 16G 4G 2G 0.5G 10G 11G
# Swap: 8G 0G 8G
# detailed memory info
cat /proc/meminfo
# key fields:
# total total RAM
# used used by applications
# free completely free
# buff/cache kernel buffers and page cache
# available estimate of memory available for new apps
# IMPORTANT: Linux uses free RAM for cache
# 'available' is more meaningful than 'free'
# Cache is reclaimed on demand, so don't panic if 'free' is low
# swap info
swapon --show # show swap devices
cat /proc/swaps
# clear cache (requires root, use with caution)
sudo sysctl vm.drop_caches=3 # free pagecache, dentries, inodes
# process memory usage
ps aux --sort=-%mem | head -10 # top memory consumersuptime e carga do sistema
uptime mostra há quanto tempo o sistema está no ar e a load average (médias de 1/5/15 minutos). A load average representa o número médio de processos esperando CPU — geralmente deve ficar abaixo do número de núcleos de CPU. O vmstat mostra estatísticas de CPU, memória e I/O em tempo real — a coluna 'r' (processos prontos para rodar) e 'si/so' (swap in/out) são indicadores-chave. iostat e sar (do pacote sysstat) fornecem I/O detalhado e dados históricos.
# system uptime and load average
uptime
# 10:30:00 up 5 days, 3:21, 2 users, load average: 0.50, 0.35, 0.25
# load average: 1min, 5min, 15min
# = average number of processes waiting for CPU
# rule of thumb: should be < number of CPU cores
# check CPU count
nproc # number of CPU cores
lscpu | grep "^CPU(s):"
# detailed load and context switches
cat /proc/loadavg
# 0.50 0.35 0.25 2/500 12345
# vmstat: system stats over time
vmstat 1 5 # every 1 second, 5 times
# procs --memory-- ---swap-- -----io---- -system-- ------cpu-----
# r b swpd free buff cache si so bi bo in cs us sy id wa
# iostat: I/O statistics (needs sysstat package)
iostat 1 # every 1 second
iostat -x 1 # extended stats
# mpstat: per-CPU statistics
mpstat -P ALL 1
# sar: historical system activity
sar -u # CPU usage history
sar -r # memory usage history
# who is logged in
who
w # with what they're doingRedes
ping e traceroute
ping testa a alcançabilidade e mede latência usando ICMP echo. -c limita a contagem (senão roda para sempre). traceroute mostra cada salto até o destino — útil para diagnosticar onde a conectividade falha. mtr combina traceroute com ping contínuo (excelente para diagnosticar problemas intermitentes). dig consulta registros DNS (mais detalhado que nslookup). nc (netcat) -z testa se uma porta TCP está aberta sem enviar dados.
# test connectivity
ping google.com
ping -c 4 google.com # 4 packets then stop
ping -i 0.5 google.com # 0.5s interval
ping -W 2 google.com # 2s timeout per packet
# ping with timestamp
ping -D google.com # unix timestamps
# check if host is reachable
ping -c 1 -W 1 host && echo "up" || echo "down"
# trace network path
traceroute google.com
traceroute -n google.com # no DNS resolution (faster)
mtr google.com # traceroute + ping (continuous)
# trace with TCP (bypasses ICMP blocking)
tcptraceroute google.com 443
# DNS lookup
dig example.com
dig +short example.com # just the IP
dig MX example.com # mail records
dig NS example.com # name servers
dig @8.8.8.8 example.com # specific DNS server
# alternative DNS tools
nslookup example.com
host example.com
host -t MX example.com
# check open ports
nc -zv google.com 443 # check if port 443 is open
nc -zv google.com 80 443 22 # check multiple portsnetstat e ss
ss é o substituto moderno do netstat — mais rápido e detalhado. -tlnp mostra portas TCP em escuta com nomes de processos (precisa de root para -p). Para achar o que usa uma porta: ss -tlnp | grep :PORTA ou lsof -i :PORTA. ip substitui ifconfig/route (do pacote iproute2). Chave: -n impede resolução de DNS (muito mais rápido). Verifique 'state established' para conexões ativas. netstat está descontinuado, mas ainda amplamente disponível.
# ss: modern socket statistics (replaces netstat)
ss -tlnp # listening TCP ports + process
ss -tunap # all TCP/UDP connections
ss -s # socket summary
# netstat: classic network statistics
netstat -tlnp # listening TCP ports
netstat -tunap # all connections
netstat -rn # routing table
netstat -i # interface statistics
# common ss/netstat flags:
# -t TCP
# -u UDP
# -l listening sockets only
# -n numeric (no DNS resolution, faster)
# -a all sockets
# -p show process using socket (needs root)
# -r routing table
# find what's listening on a port
ss -tlnp | grep :80
lsof -i :8080 # alternative
# check established connections
ss -tn state established
# show all connections to a specific host
ss -tn dst google.com
# view network interfaces
ip addr # modern
ip a # short form
ifconfig # legacy
# view routing table
ip route # modern
route -n # legacy
# view interface statistics
ip -s link
ifconfig eth0curl — cliente HTTP
curl é o cliente HTTP essencial para a linha de comando. -X define a função; -d envia dados POST; -H define headers; -L segue redirecionamentos; -O salva com o nome remoto do arquivo; -s é silencioso (para scripts); -w '%{http_code}' extrai só o código de status. Para APIs JSON, combine -H 'Content-Type: application/json' com -d. -u fornece basic auth. Para testar APIs REST, curl é o padrão universal.
# basic GET request
curl https://api.example.com/data
# save to file
curl -O https://example.com/file.zip # save with remote filename
curl -o file.zip https://example.com/file.zip # custom name
# follow redirects
curl -L https://short.url/abc
# HTTP methods
curl -X POST https://api.example.com/users
curl -X PUT -d '{"name":"Alice"}' https://api.example.com/users/1
curl -X DELETE https://api.example.com/users/1
# send data
curl -d "name=Alice&age=30" https://api.example.com/form
curl -H "Content-Type: application/json" \
-d '{"name":"Alice"}' https://api.example.com/users
# headers
curl -H "Authorization: Bearer TOKEN" \
-H "Accept: application/json" \
https://api.example.com/data
# verbose / headers only
curl -v https://example.com # verbose
curl -I https://example.com # headers only
# authentication
curl -u user:pass https://api.example.com # basic auth
curl --netrc-file ~/.netrc https://... # netrc
# download with progress bar
curl --progress-bar -O https://example.com/largefile.iso
# get HTTP status code only
curl -s -o /dev/null -w "%{http_code}" https://example.com
# retry on failure
curl --retry 3 --retry-delay 5 https://example.com
# pass query parameters
curl "https://api.example.com/search?q=linux&page=2"wget — baixar arquivos
wget baixa arquivos de forma não interativa. -c retoma downloads interrompidos (essencial para arquivos grandes). -m espelha sites (com -k para conversão de links). -r recursa com -l para profundidade. -i lê URLs de um arquivo. wget é melhor que curl para downloads recursivos/espelhamento e para retomar — o curl usa -C - para retomada. --limit-rate limita a banda. O wget lida com redirecionamentos e cookies automaticamente.
# download a file
wget https://example.com/file.zip
# download with custom name
wget -O myfile.zip https://example.com/file.zip
# download in background
wget -b https://example.com/largefile.iso
# resume interrupted download
wget -c https://example.com/largefile.iso
# mirror a website
wget -m https://example.com
wget -m -k -K -E https://example.com # convert links for local viewing
# recursive download (limited depth)
wget -r -l 2 https://example.com
# download all files of a type
wget -r -A pdf https://example.com/documents/
# continue and retry
wget -t 5 --waitretry=10 https://example.com/file.zip
# quiet mode (no output)
wget -q https://example.com/file.zip
# download from a list of URLs
wget -i urls.txt
# authentication
wget --user=user --password=pass https://example.com/protected
# set user agent
wget --user-agent="Mozilla/5.0" https://example.com
# limit download speed
wget --limit-rate=200k https://example.com/file.zip
# ignore certificate errors
wget --no-check-certificate https://example.com/file.zipip e ifconfig
ip (do iproute2) é o substituto moderno de ifconfig/route. ip a mostra endereços; ip link mostra a camada 2; ip route mostra a tabela de roteamento. Mudanças com ip são temporárias (perdidas ao reiniciar) — para persistência, edite /etc/netplan/ (Ubuntu), /etc/network/interfaces (Debian), ou use nmcli (NetworkManager). ifconfig está descontinuado, mas ainda amplamente usado. Para wireless, use iw/iwconfig.
# view network interfaces (modern)
ip addr show # all interfaces
ip a # short form
ip a show eth0 # specific interface
# view link status
ip link show
ip -s link show eth0 # with statistics
# bring interface up/down
sudo ip link set eth0 up
sudo ip link set eth0 down
# assign IP address
sudo ip addr add 192.168.1.100/24 dev eth0
sudo ip addr del 192.168.1.100/24 dev eth0
# routing table
ip route show
ip route # short form
sudo ip route add default via 192.168.1.1
# view ARP table
ip neigh # neighbors (ARP)
arp -a # legacy
# DNS configuration
cat /etc/resolv.conf
# ifconfig (legacy, still common)
ifconfig # all interfaces
ifconfig eth0 # specific interface
sudo ifconfig eth0 192.168.1.100 netmask 255.255.255.0 up
# change MAC address
sudo ip link set dev eth0 address 00:11:22:33:44:55
# view wireless info
iwconfig # wireless interfaces
iw list # wireless capabilities
# network manager (desktop)
nmcli device status
nmcli connection showConsulta DNS (dig, nslookup)
dig é a ferramenta de consulta DNS mais poderosa. +short dá saída concisa. Tipos de registro comuns: A (IPv4), AAAA (IPv6), MX (e-mail), NS (nameservers), TXT (texto/SPF), CNAME (alias). @server consulta um servidor DNS específico. -x faz consultas reversas (IP para hostname). +trace mostra o caminho completo de resolução a partir dos servidores raiz. host é uma alternativa mais simples. Checagens de propagação de DNS comparam resultados entre múltiplos servidores.
# dig: detailed DNS lookup
dig example.com
dig +short example.com # just the IP address
dig example.com A # A record (IPv4)
dig example.com AAAA # AAAA record (IPv6)
dig example.com MX # mail exchange
dig example.com NS # name servers
dig example.com TXT # TXT records (SPF, etc.)
dig example.com SOA # start of authority
# query specific DNS server
dig @8.8.8.8 example.com
dig @1.1.1.1 example.com MX
# reverse DNS lookup
dig -x 1.2.3.4
dig -x 8.8.8.8 +short
# trace DNS resolution path
dig +trace example.com
# JSON output (for scripting)
dig +json example.com
# nslookup: simpler alternative
nslookup example.com
nslookup example.com 8.8.8.8 # use specific server
# host: concise output
host example.com # IP address
host -t MX example.com # mail records
host -t NS example.com # name servers
host 8.8.8.8 # reverse lookup
# check DNS propagation
# compare results from multiple servers
for dns in 8.8.8.8 1.1.1.1 9.9.9.9; do
echo "=== $dns ==="
dig @$dns example.com +short
done
# flush DNS cache
sudo systemd-resolve --flush-caches # systemd
sudo resolvectl flush-caches # newer systemdGerenciamento de pacotes
apt (Debian/Ubuntu)
apt é a interface amigável ao dpkg/apt-get (Debian/Ubuntu). Sempre rode apt update antes de install/upgrade para atualizar a lista de pacotes. upgrade mantém pacotes; full-upgrade pode removê-los para resolver dependências. purge remove arquivos de configuração. autoremove limpa dependências órfãs. dpkg -S acha qual pacote possui um arquivo. apt-mark hold impede que um pacote seja atualizado (útil para versões fixadas).