시작하기
기본 파일 커맨드
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이 파일의 매직 바이트를 검사해 진짜 타입을 판단합니다 — 확장자보다 훨씬 신뢰적입니다. ls -F가 타입 표시자를 덧붙입니다(* 실행 파일, / 디렉터리, @ 심볼릭 링크, = 소켓). 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는 대화형 non-login 셸에서, ~/.profile이나 ~/.bash_profile은 login 셸에서 소싱됩니다. 편집 후에는 변경 적용을 위해 항상 파일을 소싱하세요. 확장 없이 단일 변수 확인에는 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는 아카이브 모드입니다(심볼릭 링크 포함 전부 보존 — 백업에 이상적). -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 커맨드(Debian/Ubuntu는 Perl 기반)가 정규식으로 일괄 이름 변경을 합니다 — mv 루프보다 훨씬 강력합니다. 참고: rename 문법은 배포판마다 다릅니다(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 *.JPG파일 제거 (rm)
rm이 파일을 영구 삭제합니다(휴지통 없음). 디렉터리에는 -r이 필요합니다. -rf는 위험합니다 — 묻지 않고 재귀 삭제합니다; 항상 경로를 다시 확인하세요. $VAR이 비어 있을 수 있으면 rm -rf /나 rm -rf $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(데이터)를 공유합니다 — 모든 링크가 제거되기 전에는 데이터가 삭제되지 않습니다. 파일시스템을 넘거나 디렉터리에 링크할 수 없습니다. 심볼 릭 링크는 경로 참조입니다 — 대상이 옮겨지거나 삭제되면 깨지지만, 파일시스템을 넘어 디렉터리에도 링크할 수 있습니다. 심볼릭 링크는 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가 상대 경로와 심볼릭 링크를 절대 정준 경로로 해석합니다. stat -c가 커스텀 출력 형식을 허용합니다(%n=이름, %s=크기, %y=mtime, %a=8진수 권한) — 스크립트에 유용합니다. 이 도구들은 경로 조작을 위한 취약한 파라미터 확장을 대체합니다.
# 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/디렉터리 목록 & 트리
ls -d */이 디렉터리만 나열합니다. tree가 시각적 계층을 줍니다 — -L이 깊이를 제한하고, -I가 패턴을 제외합니다(node_modules/.git 제외에 믿기지 않을 만큼 유용합니다). 큰 디렉터리 트리에는 빠른 개관을 위해 tree -d -L 2를 결합하세요. ls -1(숫자 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 endless 페이저
less가 표준 페이저입니다 — 뒤로 이동이 가능해 more보다 훨씬 낫습니다. 키바인딩이 vim과 유사합니다(j/k/g/G). /가 앞으로, ?가 뒤로 검색합니다. F가 'follow 모드'(tail -f처럼)로 진입해 로그를 감시합니다. lesspipe이 설정되면 less가 압축 파일을 자동 처리합니다. 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'가 특정 줄 번호를 인쇄합니다. NR(레코드 번호)이 있는 awk가 범위와 조건에 더 유연합니다. (head; tail) 트릭이 큰 파일의 양 끝을 보여줍니다. nl과 cat -n이 줄에 번호를 붙입니다. hexdump/xxd가 바이너리 파일을 16진수로 보여줍니다 — 비텍스트 파일 검사, 파일 형식 디버깅, 데이터 복구에 필수입니다.
# 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(word count)가 줄(-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=심볼릭 링크). -maxdepth가 재귀를 제한합니다(성능에 중요). -not과 -prune이 경로를 제외합니다. \( -name A -o -name B \)가 조건을 OR로 묶습니다. 셸 글롭 확장을 막으려 항상 패턴에 따옴표를 붙이세요.
# 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(KB), M(MB), G(GB). -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보다 안전합니다. -delete를 더하기 전에 항상 -print로 먼저 테스트하세요. -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 python3find 실용 레시피
이 레시피들이 find의 실전 능력을 보여줍니다. -printf가 커스텀 출력 형식을 허용합니다(%s=크기, %p=경로). -newermt가 날짜 문자열로 수정 시간에 매칭합니다. -newer가 참조 파일과 비교합니다. 깨진 심볼릭 링크 찾기는 -exec 안에서 test -e를 씁니다. 확장자별 파일 수 레시피는 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(고정 문자열)를 쓰세요.
# 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.txt정규식이 있는 grep
grep -E(또는 egrep)가 +, ?, |, ()가 백슬래시 없이 동작하는 Extended Regular Expressions를 씁니다. ^와 $가 줄 시작/끝에 고정합니다. []가 문자 클래스를 정의하고, {}가 반복을 지정합니다. -P가 \d, \w, \b, 전후방탐색이 있는 Perl-Compatible Regex(PCRE)를 켭니다 — 강력하지만 GNU 전용입니다. -F는 패턴을 고정 문자열로 다뤄(정규식 해석 없음) 리터럴 검색에 더 빠릅니다.
# 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.txtgrep 컨텍스트 & 출력
컨텍스트 flag(-B, -A, -C)가 주변 줄을 보여줍니다 — 로그 항목 이해에 필수입니다. --color가 매칭을 하이라이트합니다. -r이 재귀 검색합니다(심볼릭 링크 제외); -R은 심볼릭 링크를 따릅니다. --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 -20grep 종료 상태 & 스크립팅
grep의 종료 상태가 스크립팅에 이상적입니다: 0(매칭 발견), 1(매칭 없음), 2(오류). -q(quiet)가 순수 조건 검사를 위해 출력을 억제합니다. 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가 글롭 패턴을 씁니다. grep과 달리 rg는 기본적으로 숨김 파일과 gitignore된 파일을 건너뜁니다 — 오버라이드에는 --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가 더 깔끔한 캡처 그룹 문법의 확장 정규식을 켭니다. 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이 필드(-d 구분자와 함께 -f)나 문자 위치(-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이 문자를 변환하거나 삭제합니다(정규식이 아니라 문자 집합입니다). -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'가 8진수 권한을 보여줍니다. ls -l의 첫 문자가 파일 타입입니다(- 파일, d 디렉터리, l 심볼릭 링크, 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 — 숫자 모드
숫자(8진수) 표기: 각 자리가 소유자, 그룹, 기타를 나타냅니다. r=4, w=2, x=1 — 더하세요. 디렉터리와 실행 파일에는 755(rwxr-xr-x), 일반 파일에는 644(rw-r--r--), 개인 파일에는 600(rw-------)입니다. 웹 서버 표준은 dirs=755, files=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가 다른 파일로부터 권한을 복사합니다. 디렉터리의 스티키 비트(+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입니다. 심볼릭 링크에는 항상 -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가 root로 /etc/shadow를 수정하기 위해 필요합니다. SGID(2xxx): 실행 파일에서는 그룹 권한으로 실행되고, 디렉터리에서는 새 파일이 디렉터리의 그룹을 상속합니다(공유 프로젝트에 유용). 스티키 비트(1xxx): 디렉터리에서 파일 소유자(또는 디렉터리 소유자/root)만 파일을 삭제할 수 있습니다(/tmp에 사용). SUID/SGID 파일은 권한 상승 벡터이므로 정기적으로 감사하세요.
# 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 execute사용자 & 그룹
사용자 관리
useradd가 사용자를 만듭니다(저수준; Debian의 adduser가 더 친절한 래퍼입니다). -m이 홈 디렉터리를 만들고, -s가 셸을, -c가 전체 이름을 정하며, -G가 보조 그룹에 추가합니다. usermod -aG가 기존 것을 제거하지 않고 그룹에 추가합니다(항상 -G와 함께 -a를 쓰세요). userdel -r이 홈 디렉터리를 제거합니다. passwd가 비밀번호를 설정합니다. /etc/passwd가 사용자 정보를, /etc/shadow가 비밀번호 해시를 저장합니다.
# 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: -f1그룹 관리
그룹이 공유 접근을 위해 사용자를 조직화합니다. groupadd/groupdel/groupmod가 그룹을 관리합니다. usermod -aG(그룹에 추가)가 사용자 추가의 표준 방법입니다 — -a가 없으면 보조 그룹 전부를 교체해 버립니다. gpasswd가 대안 도구입니다. /etc/group이 그룹 정의를 저장합니다. newgrp가 다른 기본 그룹으로 새 셸을 시작합니다(그룹 소유가 되어야 할 파일을 만들 때 유용).
# 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/group비밀번호 관리
passwd가 비밀번호를 바꿉니다. -l이 계정을 잠그고(해시에 ! 추가), -u가 잠금을 풉니다. -e가 다음 로그인 시 비밀번호 변경을 강제합니다. chage가 비밀번호 노화 정책을 관리합니다: -M(최대 일수), -m(최소 일수), -W(경고 일수), -E(만료일). 비밀번호 해시는 /etc/passwd가 아니라 /etc/shadow에(root만 읽을 수 있음) 저장됩니다. 좋은 비밀번호 정책은 복잡성 요건과 함께 정기 변경을 요구합니다.
# 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/shadow사용자 정보 커맨드
whoami가 현재 사용자명을 보여주고, id가 uid/gid/그룹을 보여줍니다. who가 로그인한 모든 사용자를 나열하고, w가 실행 중인 것을 더합니다. last가 /var/log/wtmp로부터 로그인 히스토리를 보여주고, lastb가 /var/log/btmp로부터 실패 시도를 보여줍니다. getent passwd가 사용자 데이터베이스를 조회합니다(설정돼 있다면 LDAP 포함). 이 커맨드들은 시스템 관리와 사용자 활동 감사에 필수입니다.
# 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 & sudo
su가 사용자를 전환합니다(대상 사용자의 비밀번호 필요); sudo가 root로 커맨드를 실행합니다(자신의 비밀번호 필요). su -가 로그인 셸을 시작합니다(대상 사용자의 프로필 로드). sudo가 감사에 권장됩니다: 커맨드가 /var/log/auth.log에 기록됩니다. visudo가 /etc/sudoers를 안전하게 편집합니다(저장 전 문법 검증). NOPASSWD 규칙은 편하지만 보안을 낮춥니다. sudo !!가 마지막 커맨드를 root로 반복합니다 — 클래식한 '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)프로세스 관리
ps — 프로세스 목록
ps가 프로세스 스냅샷을 보여줍니다. aux(BSD)와 -ef(System V)가 두 가지 흔한 스타일입니다. 'ps aux | grep' 패턴이 만능입니다(grep에 매칭되는 것을 피하려 [n]ginx 트릭을 쓰세요). pstree가 부모-자식 관계를 보여줍니다. --sort=-%mem이 메모리 사용량으로 정렬합니다(리소스 독식자 찾기). 핵심 상태: R=실행 중, S=수면, D=중단 불가 수면, Z=좀비, T=정지. 실시간 모니터링에는 top이나 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 & htop
top이 내장 실시간 프로세스 모니터입니다. 핵심 커맨드: M(메모리 정렬), P(CPU 정렬), k(죽이기), q(나가기). -b(batch) 모드가 스크립팅용 텍스트를 출력합니다. htop이 더 우월한 대안입니다(색상, 스크롤, 마우스 지원, 트리 뷰) — apt install htop으로 설치하세요. glances가 포괄적인 시스템 개관을 제공합니다. 무엇이 리소스를 소비하는지 찾을 때 %CPU나 %MEM으로 정렬된 top/htop이 필수 도구입니다.
# 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 & killall
kill이 PID로 시그널을 보내고, killall/pkill이 이름으로 보냅니다. 항상 먼저 SIGTERM(기본값)을 시도하세요 — 정상적인 정리를 허용합니다. SIGKILL(-9)은 강력하고 즉각적입니다; 프로세스가 잡을 수 없어 리소스가 나쁜 상태로 남을 수 있습니다. 최후의 수단으로 쓰세요. pkill -f가 전체 커맨드 라인에 매칭합니다. kill -l이 모든 시그널을 나열합니다. 'kill; sleep; kill -9' 패턴이 강제 전에 프로세스가 정리할 기회를 줍니다.
# 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) # alternative백그라운드 작업 & 잡 제어
&를 붙이면 백그라운드에서 실행됩니다. jobs가 활성 작업을 나열하고, fg/bg가 전경과 배경 사이를 옮깁니다. Ctrl+Z가 전경 작업을 일시중단합니다. wait이 백그라운드 작업이 끝날 때까지 막습니다. nohup과 disown이 모두 터미널이 닫혀도 프로세스가 죽지 않게 합니다 — 새 커맨드에는 nohup, 이미 실행 중인 것에는 disown입니다. 지속적인 작업에는 대신 tmux나 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 & renice — 프로세스 우선순위
nice 값은 -20(가장 높은 우선순위)부터 19(가장 낮음)까지입니다. 일반 사용자는 우선순위를 낮추기만 할 수 있고(양수), root는 올릴 수 있습니다(음수). 기본값은 0입니다. nice가 우선순위와 함께 프로세스를 시작하고, renice가 실행 중인 프로세스를 바꿉니다. I/O 집약 작업에는 ionice가 디스크 I/O 우선순위를 제어합니다(클래스: 1=실시간, 2=최선 노력, 3=유휴). cpulimit이 CPU 사용을 스로틀합니다 — 방해해서는 안 되는 백그라운드 작업에 유용합니다.
# 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% CPU/proc 파일시스템
/proc은 커널과 프로세스 정보를 노출하는 가상 파일시스템입니다(디스크 저장 없음). /proc/PID/가 프로세스별 데이터를 담습니다. /proc/cpuinfo와 /proc/meminfo가 하드웨어를 보여줍니다. /proc/sys/가 튜닝 가능한 커널 매개변수를 담습니다(sysctl과 동등). /proc/sys/에 쓰면 커널 설정이 즉시 바뀝니다(지속에는 sysctl 사용). /proc/mounts가 현재 마운트된 파일시스템을 보여줍니다. 이것이 사용자 공간과 커널 사이의 주요 인터페이스입니다.
# /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 version시스템 정보
uname & hostname
uname이 커널 정보를 보여줍니다(전부는 -a). hostname이 시스템 이름을 보여주거나 설정합니다 — hostnamectl set-hostname이 지속되게 합니다. /etc/os-release가 배포판을 식별하는 표준 방법입니다(모든 현대 리눅스에서 동작). lscpu가 상세한 CPU 아키텍처 정보를 줍니다. dmidecode가 BIOS/SMBIOS 데이터를 읽습니다. 이 커맨드들이 다루는 대상을 이해하는 모든 시스템 관리 작업의 첫 단계입니다.
# 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 — 디스크 여유 공간
df가 파일시스템 디스크 공간을 보고합니다. -h(사람이 읽는 형식)가 필수입니다. -T가 파일시스템 타입을 보여줍니다(ext4, xfs, btrfs, tmpfs, nfs). -i가 inode 사용량을 보여줍니다 — 공간이 남아 있어도 inode가 다 차면 파일을 만들 수 없습니다(많은 작은 파일에서 흔함). -x가 파일시스템 타입을 제외합니다(tmpfs 같은 가상 파일시스템 필터링에 유용). 디스크가 가득 차면 먼저 df -h를 확인하고, 그다음 공간을 잡아먹는 디렉터리를 찾으려 du를 쓰세요.
# 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 — 디스크 사용량
du가 디스크 사용량을 측정합니다. -s(요약)는 총계만 보여주고, -h는 사람이 읽게 합니다. du -sh */가 바로 아래 서브디렉터리 크기를 줍니다. sort -rh가 사람이 읽는 값으로 정렬합니다. --apparent-size가 실제 디스크 블록 대신 논리 파일 크기를 보여줍니다. --exclude가 패턴을 건너뜁니다. 무엇이 디스크 공간을 잡아먹는지 찾는 워크플로우: df -h(어느 파일시스템이 가득한가) → du -sh *(어느 디렉터리인가) → find(어느 파일인가).
# 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 — 메모리 사용량
free가 메모리 사용량을 보여줍니다. 'available' 컬럼이 가장 의미 있습니다 — 스와핑 없이 새 애플리케이션을 시작할 수 있는 메모리를 추정합니다. 리눅스는 의도적으로 남는 RAM을 캐시(buff/cache)로 써 디스크 읽기를 빠르게 합니다; 이는 수요에 따라 회수되므로 낮은 'free'는 정상입니다. 스왑 사용량은 감시해야 합니다 — 활발한 스와핑(vmstat의 si/so)이 있는 높은 스왑 사용은 메모리 압박을 나타냅니다.
# 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 & 시스템 부하
uptime이 시스템 실행 시간과 로드 평균(1/5/15분 평균)을 보여줍니다. 로드 평균은 CPU를 기다리는 프로세스의 평균 수를 나타냅니다 — 보통 CPU 코어 수 아래여야 합니다. vmstat가 실시간 CPU, 메모리, I/O 통계를 보여줍니다 — 'r' 컬럼(실행 가능한 프로세스)과 'si/so'(스왑 인/아웃)가 핵심 지표입니다. iostat과 sar(sysstat 패키지)가 상세한 I/O와 이력 데이터를 제공합니다.
# 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 doing네트워킹
ping & traceroute
ping이 ICMP echo로 도달 가능성을 테스트하고 지연을 측정합니다. -c가 횟수를 제한합니다(없으면 영원히 실행됩니다). traceroute가 목적지까지의 각 홉을 보여줍니다 — 연결이 어디서 실패하는지 진단에 유용합니다. mtr이 traceroute와 지속적인 ping을 결합합니다(간헐적 문제 진단에 탁월). dig가 DNS 레코드를 조회합니다(nslookup보다 상세). nc(netcat) -z가 데이터를 보내지 않고 TCP 포트가 열려 있는지 검사합니다.
# 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 & ss
ss가 netstat의 현대적 교체물입니다 — 더 빠르고 상세합니다. -tlnp가 프로세스 이름과 함께 리슨 중인 TCP 포트를 보여줍니다(-p에는 root 필요). 포트를 쓰는 것 찾기: ss -tlnp | grep :PORT 또는 lsof -i :PORT. ip가 ifconfig/route를 교체합니다(iproute2 패키지). 핵심: -n이 DNS 해석을 막아 훨씬 빠릅니다. 활성 연결에는 'state established'를 확인하세요. netstat은 폐기됐지만 여전히 널리 있습니다.
# 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 — HTTP 클라이언트
curl이 커맨드라인의 필수 HTTP 클라이언트입니다. -X가 메서드를 정하고, -d가 POST 데이터를 보내며, -H가 헤더를 정하고, -L이 리다이렉트를 따르며, -O가 원격 파일명으로 저장하고, -s는 silent입니다(스크립팅용), -w '%{http_code}'가 상태 코드만 추출합니다. JSON API에는 -H 'Content-Type: application/json'과 -d를 결합하세요. -u가 basic 인증을 제공합니다. REST API 테스트에는 curl이 만능 표준입니다.
# 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 — 파일 다운로드
wget이 비대화형으로 파일을 내려받습니다. -c가 중단된 다운로드를 재개합니다(큰 파일에 필수). -m이 웹사이트를 미러링합니다(링크 변환은 -k). -r이 재귀하며 깊이는 -l입니다. -i가 파일에서 URL을 읽습니다. 재귀/미러 다운로드와 재개에는 wget이 curl보다 낫습니다 — curl의 재개는 -C -입니다. --limit-rate가 대역폭을 스로틀합니다. wget이 리다이렉트와 쿠키를 자동 처리합니다.
# 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 & ifconfig
ip(iproute2 제공)가 ifconfig/route의 현대적 교체물입니다. ip a가 주소를, ip link가 2계층을, ip route가 라우팅 테이블을 보여줍니다. ip의 변경은 임시입니다(재부팅 시 사라짐) — 지속을 위해서는 /etc/netplan/(Ubuntu), /etc/network/interfaces(Debian)을 편집하거나 nmcli(NetworkManager)를 쓰세요. ifconfig은 폐기됐지만 여전히 널리 쓰입니다. 무선에는 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 showDNS 조회 (dig, nslookup)
dig가 가장 강력한 DNS 조회 도구입니다. +short가 간결한 출력을 줍니다. 흔한 레코드 타입: A(IPv4), AAAA(IPv6), MX(메일), NS(네임서버), TXT(텍스트/SPF), CNAME(별칭). @server가 특정 DNS 서버에 조회합니다. -x가 역방향 조회(IP→호스트명)를 합니다. +trace가 루트 서버로부터의 전체 해석 경로를 보여줍니다. host가 더 단순한 대안입니다. DNS 전파 검사는 여러 서버의 결과를 비교합니다.
# 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 systemd패키지 관리
apt (Debian/Ubuntu)
apt가 dpkg/apt-get의 사용자 친화적 프런트엔드입니다(Debian/Ubuntu). 패키지 목록을 새로 고치려 install/upgrade 전에 항상 apt update를 실행하세요. upgrade는 패키지를 유지하고, full-upgrade는 의존성 해결을 위해 패키지를 제거할 수 있습니다. purge가 설정 파일을 제거합니다. autoremove가 고아 의존성을 정리합니다. dpkg -S가 파일을 소유한 패키지를 찾습니다. apt-mark hold가 패키지 업그레이드를 막습니다(고정 버전에 유용).
# update package list
sudo apt update
# upgrade installed packages
sudo apt upgrade # upgrade without removing
sudo apt full-upgrade # upgrade, may remove packages
sudo apt dist-upgrade # alias for full-upgrade
# install packages
sudo apt install nginx
sudo apt install nginx=1.18* # specific version
sudo apt install -y nginx # no prompt
# remove packages
sudo apt remove nginx # remove but keep config
sudo apt purge nginx # remove including config
sudo apt autoremove # remove unused dependencies
sudo apt clean # clean downloaded packages
# search for packages
apt search nginx
apt-cache search web server
# show package info
apt show nginx
apt-cache policy nginx # available versions
# list installed packages
apt list --installed
dpkg -l | grep nginx
# list files installed by a package
dpkg -L nginx
dpkg -S /usr/bin/curl # which package owns a file
# add PPA (Ubuntu)
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
# hold package (prevent upgrade)
sudo apt-mark hold nginx
sudo apt-mark unhold nginxdnf/yum (RHEL/Fedora/CentOS)
dnf가 현대 Fedora/RHEL/CentOS 8+에서 yum을 교체합니다. 커맨드가 비슷합니다. dnf provides(또는 yum provides)가 파일을 제공하는 패키지를 찾습니다 — 없는 의존성을 찾는 데 필수입니다. rpm -ql이 설치된 패키지의 파일을 나열하고, rpm -qf가 파일의 소유자를 찾습니다. EPEL이 RHEL/CentOS에 추가 패키지를 제공합니다. dnf groupinstall이 패키지 그룹(Development Tools 같은)을 설치합니다. yum은 많은 시스템에서 dnf로의 심볼릭 링크로 여전히 동작합니다.
# dnf: modern Fedora/RHEL/CentOS
sudo dnf install nginx
sudo dnf update # update all packages
sudo dnf upgrade # same as update
sudo dnf remove nginx
# search
dnf search nginx
dnf list available # all available packages
dnf list installed # installed packages
# package info
dnf info nginx
dnf provides /usr/bin/curl # which package provides a file
# clean cache
sudo dnf clean all
# group install
dnf groupinstall "Development Tools"
dnf group list
# yum: older CentOS/RHEL (still available)
sudo yum install nginx
sudo yum update
sudo yum remove nginx
yum search nginx
yum provides /usr/bin/curl
# enable EPEL repository (Extra Packages for Enterprise Linux)
sudo dnf install epel-release
# list dependencies
dnf repoquery --requires nginx
dnf repoquery --deplist nginx
# downgrade a package
sudo dnf downgrade nginx
# view package files
rpm -ql nginx # files installed by package
rpm -qi nginx # package info
rpm -qf /usr/bin/curl # which package owns filepacman (Arch Linux)
pacman이 Arch Linux의 패키지 매니저입니다. -Syu가 필수 시스템 업데이트 커맨드입니다(항상 전체 시스템을 갱신, 부분은 금지). -S가 설치하고, -R이 제거하며, -Q가 로컬을 조회합니다. -Rs가 쓰이지 않는 의존성과 함께 제거하고, -Rns가 설정까지 제거합니다. Arch는 롤링 릴리스입니다 — 부분 업그레이드는 지원되지 않으며 시스템을 깨뜨릴 수 있습니다. AUR(Arch User Repository)이 yay/paru 같은 헬퍼를 통해 커뮤니티 패키지를 제공합니다.
# update system
sudo pacman -Syu # sync repos + upgrade all
# ALWAYS update the full system on Arch
# install packages
sudo pacman -S nginx
sudo pacman -S --needed nginx # don't reinstall if up to date
# remove packages
sudo pacman -R nginx # remove package only
sudo pacman -Rs nginx # remove + unused deps
sudo pacman -Rns nginx # remove + deps + config
# search packages
pacman -Ss nginx # search repos
pacman -Qs nginx # search installed
# package info
pacman -Si nginx # info from repos
pacman -Qi nginx # info from installed
pacman -Ql nginx # list files
pacman -Qo /usr/bin/curl # which package owns file
# list orphaned packages
pacman -Qdt
# clean cache
sudo pacman -Sc # clean old packages
sudo pacman -Scc # clean all cache
# query local database
pacman -Q # all installed packages
pacman -Qe # explicitly installed
pacman -Qm # foreign (AUR) packages
# AUR (Arch User Repository)
# install yay or paru for AUR support
yay -S package-name # install from AUR
# downgrade a package
sudo pacman -U /var/cache/pacman/pkg/package-1.0-1.x86_64.pkg.tar.zst패키지 찾기
'command not found'가 나왔을 때 키워드로(apt/dnf search)나 파일로(apt-file/dnf provides/pacman -F) 패키지를 찾는 것이 필수입니다. '이 파일을 어느 패키지가 소유하는가' 질의(dpkg -S / rpm -qf / pacman -Qo)가 설치된 것을 이해하는 데 매우 유용합니다. apt-file(Debian)과 pacman -F(Arch)가 아직 설치되지 않은 패키지의 파일 데이터베이스를 검색합니다 — 필요한 헤더나 라이브러리를 제공하는 패키지를 찾는 데 유용합니다.
# Debian/Ubuntu
apt search keyword
apt-cache search keyword
apt list --installed | grep keyword
# RHEL/Fedora
dnf search keyword
yum search keyword
# Arch
pacman -Ss keyword
# search by file name/path
# Debian: apt-file (separate package)
sudo apt install apt-file
sudo apt-file update
apt-file find /usr/bin/curl
apt-file search curl.h
# RHEL/Fedora
dnf provides /usr/bin/curl
dnf provides *curl.h
yum whatprovides /usr/bin/curl
# Arch
pacman -F /usr/bin/curl
pacman -Fy # update file database first
# check if package is installed
dpkg -l | grep nginx # Debian
rpm -q nginx # RHEL
pacman -Q nginx # Arch
# list files installed by a package
dpkg -L nginx # Debian
rpm -ql nginx # RHEL
pacman -Ql nginx # Arch
# find which package owns a file
dpkg -S /usr/bin/curl # Debian
rpm -qf /usr/bin/curl # RHEL
pacman -Qo /usr/bin/curl # Arch
# show package dependencies
apt-cache depends nginx # Debian
dnf repoquery --requires nginx # RHEL
pacman -Si nginx # Arch리포지터리 관리
리포지터리가 패키지 소스입니다. Debian/Ubuntu에서는 PPA(Personal Package Archive)가 서드파티 소프트웨어를 제공합니다 — 패키지 검증을 위해 항상 서명 키를 추가하세요. /etc/apt/sources.list.d/가 커스텀 리포 파일을 담습니다. RHEL/Fedora에서는 dnf config-manager가 리포를 관리하며, RHEL에는 EPEL이 필수입니다. Arch에서는 /etc/pacman.conf를 편집하세요. 악의적인 패키지 설치를 막으려 항상 GPG 키를 검증하세요. apt policy와 dnf repolist가 설정된 리포지터리를 보여줍니다.
# Debian/Ubuntu: add repository
sudo add-apt-repository ppa:deadsnakes/ppa
sudo add-apt-repository "deb https://packages.example.com/ubuntu jammy main"
# remove repository
sudo add-apt-repository --remove ppa:deadsnakes/ppa
# add repository manually
echo "deb https://packages.example.com/ubuntu jammy main" | \
sudo tee /etc/apt/sources.list.d/example.list
# add signing key (Debian)
wget -qO- https://example.com/key.gpg | \
sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/example.gpg
# list repositories
apt policy # show configured repos
grep -r "" /etc/apt/sources.list.d/
# RHEL/Fedora: enable repository
sudo dnf config-manager --add-repo https://example.com/repo.repo
sudo dnf install epel-release # enable EPEL
sudo dnf repolist # list enabled repos
sudo dnf repolist all # list all repos
# enable/disable a repo
sudo dnf config-manager --set-enabled epel
sudo dnf config-manager --set-disabled epel
# Arch: edit /etc/pacman.conf
# [custom]
# Server = https://example.com/$repo/os/$arch
# verify package integrity
dpkg --verify # Debian
rpm -Va # RHEL서비스 관리 (systemd)
서비스 제어
systemctl이 systemd 서비스를 관리합니다. start/stop/restart가 기본 연산입니다. reload가 전체 재시작 없이 설정을 다시 읽으라 시그널을 보냅니다(우아하게). status가 현재 상태와 최근 로그를 보여줍니다. mask는 서비스가 (수동으로도) 시작되는 것을 완전히 막습니다 — disable보다 강력합니다. is-active와 is-enabled가 스크립트에 유용합니다(활성/활성화면 0 반환).
# start/stop/restart services
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx # reload config without restart
# try-restart (only if running)
sudo systemctl try-restart nginx
# reload or restart (reload if possible, otherwise restart)
sudo systemctl reload-or-restart nginx
# send signal to service
sudo systemctl kill nginx
sudo systemctl kill -s HUP nginx
# check service status
sudo systemctl status nginx
systemctl is-active nginx # active/inactive
systemctl is-enabled nginx # enabled/disabled
systemctl is-failed nginx # failed/running
# show service logs (recent)
sudo systemctl status nginx
# mask a service (prevent from starting)
sudo systemctl mask nginx
sudo systemctl unmask nginx
# reset failed state
sudo systemctl reset-failed
# emergency: reboot/poweroff
sudo systemctl reboot
sudo systemctl poweroff
sudo systemctl halt
sudo systemctl suspend서비스 상태 & 세부
systemctl status가 포괄적인 뷰를 줍니다: 상태, PID, 메모리/CPU 사용, 최근 로그. systemctl cat이 유닛 파일을 보여줍니다(오버라이드 포함). systemctl edit이 원본을 수정하지 않고 drop-in 오버라이드 파일을 만듭니다 — 벤더 제공 서비스 커스터마이징에 안전합니다. 유닛 파일을 편집한 뒤에는 변경을 systemd에 알리도록 daemon-reload를 실행하세요. list-dependencies가 서비스가 무엇을 필요로 하는지 보여줍니다.
# detailed status
systemctl status nginx
# Shows: loaded state, active state, recent log entries, cgroup info
# just the active state
systemctl is-active nginx # "active" or "inactive"
# is it enabled at boot?
systemctl is-enabled nginx # "enabled" or "disabled"
# check if service failed
systemctl is-failed nginx
# list dependencies
systemctl list-dependencies nginx
# show service file
systemctl cat nginx
systemctl cat nginx.service
# show service properties
systemctl show nginx
systemctl show -p ExecStart nginx
# view service file location
systemctl show -p FragmentPath nginx
# edit service file (override)
sudo systemctl edit nginx # creates override file
sudo systemctl edit --full nginx # edit full unit file
# reload systemd after editing unit files
sudo systemctl daemon-reload
# list sockets
systemctl list-sockets
# check all failed services
systemctl --failed서비스 활성화/비활성화
enable이 서비스가 부팅 시 시작되게 합니다(심볼릭 링크 생성)이고, disable이 심볼릭 링크를 제거합니다. --now가 enable/disable을 start/stop과 결합합니다. list-unit-files가 사용 가능한 모든 서비스를 보여주고(설치됐지만 실행 중이 아닐 수도), list-units가 로드/활성인 것을 보여줍니다. 기본 타깃(multi-user = 텍스트 모드, graphical = GUI)이 전통적 런레벨을 대체합니다. 상태별 필터에는 --state=을 쓰세요.
# enable service to start at boot
sudo systemctl enable nginx
# enable and start in one command
sudo systemctl enable --now nginx
# disable (don't start at boot)
sudo systemctl disable nginx
# disable and stop in one command
sudo systemctl disable --now nginx
# re-enable (apply symlink changes)
sudo systemctl reenable nginx
# check if enabled
systemctl is-enabled nginx
# list enabled services
systemctl list-unit-files --state=enabled
# list all service unit files
systemctl list-unit-files --type=service
# list running services
systemctl list-units --type=service --state=running
# list all loaded services
systemctl list-units --type=service
# list services by state
systemctl list-units --type=service --state=failed
systemctl list-units --type=service --state=exited
# default boot target
systemctl get-default # usually graphical.target or multi-user.target
# change boot target
sudo systemctl set-default multi-user.target # text mode (runlevel 3)
sudo systemctl set-default graphical.target # GUI mode (runlevel 5)서비스 나열 & 필터링
list-units가 현재 메모리에 로드된 것을, list-unit-files가 디스크에 설치된 것을 보여줍니다. --type이 유닛 타입으로(service, socket, timer, mount, target), --state가 상태로(running, exited, failed, enabled, disabled) 필터합니다. 타이머(systemd timers)가 cron job의 systemd 네이티브 교체물입니다 — 의존성 기반 스케줄링을 지원하고 list-timers로 보입니다. --reverse가 유닛에 의존하는 것을 보여줍니다.
# list all active units
systemctl list-units
# list only services
systemctl list-units --type=service
# list by state
systemctl list-units --type=service --state=running
systemctl list-units --type=service --state=exited
systemctl list-units --type=service --state=failed
# list all unit files (installed)
systemctl list-unit-files --type=service
# list by state (unit files)
systemctl list-unit-files --state=enabled
systemctl list-unit-files --state=disabled
systemctl list-unit-files --state=masked
# list by target (runlevel)
systemctl list-units --type=target
# list sockets
systemctl list-units --type=socket
systemctl list-sockets
# list timers (replaces cron for many tasks)
systemctl list-timers
systemctl list-timers --all
# list mounts
systemctl list-units --type=mount
# show all units (including inactive)
systemctl list-units --all
# show specific unit type
systemctl list-units --type=service --all
# count services by state
systemctl list-units --type=service --no-legend | wc -l
systemctl list-units --type=service --state=running --no-legend | wc -l
# find services that depend on a unit
systemctl list-dependencies --reverse nginxjournalctl — 시스템 로그
journalctl이 systemd 저널(구조화 로깅)을 조회합니다. -f가 실시간으로 따릅니다. -u가 유닛(서비스)으로 필터합니다. -b가 부트로 필터합니다(-b -1 = 이전 부트). --since/--until이 유연한 시간 표현을 씁니다. -p가 우선순위로 필터합니다(emerg부터 debug까지). 저널은 재부트에 걸쳐 지속됩니다(/var/log/journal/에 저장). 디스크 사용 제어에는 --vacuum-time과 --vacuum-size. journalctl이 systemd 시스템에서 /var/log/messages를 대체합니다.
# view all logs (newest last)
journalctl
# follow logs (like tail -f)
journalctl -f
# today's logs
journalctl --since today
journalctl -u nginx --since today
# specific time range
journalctl --since "2024-01-01" --until "2024-01-02"
journalctl --since "1 hour ago"
journalctl --since "30 min ago"
# logs for a specific service
journalctl -u nginx
journalctl -u nginx -f # follow
journalctl -u nginx --since "1 hour ago"
# logs for current boot
journalctl -b # current boot
journalctl -b -1 # previous boot
journalctl --list-boots # list all boots
# filter by priority
journalctl -p err # errors only
journalctl -p warning # warnings and above
# 0=emerg, 1=alert, 2=crit, 3=err, 4=warning, 5=notice, 6=info, 7=debug
# filter by process
journalctl _PID=1234
journalctl _UID=1000
# show kernel messages only
journalctl -k
# output format
journalctl -o json # JSON format
journalctl -o short-iso # ISO timestamps
journalctl --no-pager # no pager (for scripts)
# clear old logs
sudo journalctl --vacuum-time=7d # keep last 7 days
sudo journalctl --vacuum-size=100M # keep 100MB max예약 작업 (Cron)
crontab 기본
crontab -e가 예약 작업을 편집합니다. 형식: 분 시 일-of-월 월 요일 커맨드. *가 '매번'입니다. */N이 'N마다'입니다. Cron은 최소 환경으로 실행됩니다 — 커맨드와 스크립트에는 항상 절대 경로를 쓰세요. 스크립트는 PATH를 명시적으로 설정해야 합니다. 출력은 사용자에게 이메일로(crontab의 MAILTO 설정) 가거나 로그 파일로 리다이렉트하세요. 시스템 전역 작업은 /etc/crontab이나 /etc/cron.*/ 디렉터리에 둡니다.
# edit your crontab
crontab -e
# list your crontab entries
crontab -l
# remove all crontab entries
crontab -r
# edit another user's crontab (requires root)
sudo crontab -u alice -e
sudo crontab -u alice -l
# crontab entry format:
# minute hour day-of-month month day-of-week command
# 0-59 0-23 1-31 1-12 0-6 (0=Sunday)
#
# * * * * * command to execute
# | | | | |
# | | | | +----- day of week (0-7) (0 or 7 is Sunday)
# | | | +------- month (1-12)
# | | +--------- day of month (1-31)
# | +----------- hour (0-23)
# +------------- minute (0-59)
# examples:
# run every day at 2:30 AM
30 2 * * * /home/user/backup.sh
# run every Monday at 9 AM
0 9 * * 1 /home/user/weekly-report.sh
# run every 15 minutes
*/15 * * * * /home/user/check.sh
# run at reboot
@reboot /home/user/startup.sh
# system-wide cron: /etc/crontab
# adds a user column:
# minute hour day month week USER command
*/30 * * * * root /usr/local/bin/check.sh
# cron directories (run all scripts inside)
/etc/cron.daily/ # daily
/etc/cron.hourly/ # hourly
/etc/cron.weekly/ # weekly
/etc/cron.monthly/ # monthlyCron 스케줄 문법
Cron은 5 필드를 씁니다: 분(0-59), 시(0-23), 일-of-월(1-31), 월(1-12), 요일(0-7, 0과 7이 일요일). *가 매번이고, */N이 N마다이며, 쉼표가 값을 구분하고, 대시가 범위를 정의합니다. 요일과 일-of-월이 둘 다 지정되면 AND가 아니라 OR됩니다. 월말 트릭이 내일이 1일인지 검사합니다. 실제 작업 배포 전에는 항상 간단한 echo로 cron 스케줄을 테스트하세요.
# every minute
* * * * * command
# every 5 minutes
*/5 * * * * command
# every hour at minute 0
0 * * * * command
# every day at midnight
0 0 * * * command
# every day at 2:30 AM
30 2 * * * command
# every Monday at 8 AM
0 8 * * 1 command
# every weekday (Mon-Fri) at 9 AM
0 9 * * 1-5 command
# every weekend (Sat and Sun) at 10 AM
0 10 * * 0,6 command
# every month on the 1st at midnight
0 0 1 * * command
# every quarter (Jan, Apr, Jul, Oct) on the 1st
0 0 1 1,4,7,10 * command
# every 15 minutes during business hours
*/15 9-17 * * 1-5 command
# twice a day (midnight and noon)
0 0,12 * * * command
# every 2 hours
0 */2 * * * command
# last day of month (tricky — use date check)
0 0 28-31 * * [ "$(date +%d -d tomorrow)" = "01" ] && /script.sh
# run on specific date (Jan 1 at midnight)
0 0 1 1 * command특수 cron 문자열
특수 문자열(@daily, @weekly 등)이 흔한 스케줄의 축약입니다 — 5 필드 형식보다 읽기 쉽습니다. @reboot은 시스템 부팅 시 한 번 실행됩니다. MAILTO가 출력이 이메일로 갈 곳을 제어합니다 — 끄려면 빈 값으로. Cron은 최소 환경을 씁니다(제한된 PATH, 셸 프로필 없음) — PATH를 항상 명시적으로 설정하거나 절대 경로를 쓰세요. 출력 리다이렉션이 필수입니다: 없으면 출력이 이메일로 가거나 잃어버립니다.
# predefined special strings (GNU cron)
@reboot command # run once at startup
@yearly command # once a year: 0 0 1 1 *
@annually command # same as @yearly
@monthly command # once a month: 0 0 1 * *
@weekly command # once a week: 0 0 * * 0
@daily command # once a day: 0 0 * * *
@midnight command # same as @daily
@hourly command # once an hour: 0 * * * *
# examples
@reboot /home/user/startup.sh
@daily /home/user/backup.sh >> /var/log/backup.log 2>&1
@hourly /usr/local/bin/health-check.sh
# set MAILTO for email notifications
MAILTO="[email protected]"
@daily /home/user/report.sh
# disable email (discard output)
MAILTO=""
@daily /home/user/cleanup.sh > /dev/null 2>&1
# environment variables in crontab
PATH=/usr/local/bin:/usr/bin:/bin
SHELL=/bin/bash
HOME=/home/user
@daily /home/user/script.sh
# redirect output to log
@daily /home/user/script.sh >> /home/user/cron.log 2>&1
# log with timestamp
@daily echo "$(date): starting" >> /home/user/cron.log; /home/user/script.sh >> /home/user/cron.log 2>&1
# check cron service is running
systemctl status cron
systemctl status crondanacron
anacron은 항상 켜져 있지 않은 기기(노트북, 데스크톱)를 위해 설계됐습니다. cron과 달리 시스템 부팅 시 놓친 작업을 실행합니다. 일/주/월 단위만 지원합니다. delay 필드가 모든 작업이 동시에 시작되는 것을 막으려 무작위 대기를 더합니다. systemd 타이머가 현대적 대안입니다 — cron식 스케줄링을 지원하고, 놓친 작업을 실행하며(Persistent=true), journalctl과 통합해 로깅합니다.
# anacron: run periodic jobs even if system was off
# /etc/anacrontab format:
# period delay job-id command
# 1 5 daily /home/user/daily.sh
# 7 10 weekly /home/user/weekly.sh
# 30 15 monthly /home/user/monthly.sh
# view anacron config
cat /etc/anacrontab
# anacron directories (system-wide)
ls /etc/cron.daily/
ls /etc/cron.weekly/
ls /etc/cron.monthly/
# run anacron manually
sudo anacron -d # run jobs in foreground with debug
sudo anacron -f # force run all jobs
sudo anacron -u # update timestamps only (don't run)
# run a specific job
sudo anacron -j daily # run the 'daily' job
# check when jobs last ran
ls -l /var/spool/anacron/
# difference between cron and anacron:
# cron:
# - requires system to be running at scheduled time
# - minimum resolution: 1 minute
# - per-user crontabs
#
# anacron:
# - catches up missed jobs after downtime
# - minimum resolution: 1 day
# - system-wide only (runs as root)
# - good for laptops/desktops that aren't always on
# systemd timers: modern alternative to cron
systemctl list-timers
sudo systemctl enable --now mytask.timerat — 일회성 예약 작업
at이 일회성 커맨드를 예약합니다(cron의 반복 스케줄과 다름). 시각은 절대(오전 10:30, 자정)나 상대(now + 30분)일 수 있습니다. atq가 대기 중인 작업을 나열하고, atrm이 제거합니다. batch는 시스템 부하가 0.8 미만일 때 실행됩니다(설정 가능). at 작업은 사용자의 환경으로 실행됩니다. atd 서비스가 필요합니다. 알림, 지연 작업, 로그인을 유지하지 않고 종료 예약에 유용합니다.
# schedule a command for later
echo "backup.sh" | at midnight
echo "shutdown -h now" | at 2am tomorrow
# interactive scheduling
at 2:30 PM
at> /home/user/report.sh
at> Ctrl+D # press Ctrl+D to submit
# schedule relative to now
at now + 30 minutes
at> echo "30 min passed" > /tmp/notice.txt
at> Ctrl+D
at now + 2 hours
at now + 1 day
at now + 1 week
# schedule for a specific time
at 10:30 AM
at 10:30 AM tomorrow
at 10:30 AM 2025-12-25
at 10:30 AM Dec 25
# list pending jobs
atq
at -l
# view a specific job
at -c 5 # show job #5
# remove a job
atrm 5 # remove job #5
at -d 5 # alternative
# batch: run when load is low
batch
at> /home/user/heavy-computation.sh
at> Ctrl+D
# enable atd service
sudo systemctl enable --now atd
# check atd is running
systemctl status atd아카이브 & 압축
tar — 생성 & 추출
tar가 파일을 단일 아카이브로 묶습니다(기본 압축 없음). flag는 연상 기호입니다: c=생성, x=추출, t=목록, f=파일, v=상세. -C가 추출 디렉터리를 지정합니다. --exclude가 패턴을 건너뜁니다. tar가 파일 권한, 소유권, 타임스탬프를 보존합니다. 신뢰할 수 없는 소스로부터 추출 전에는 항상 tar -tf로 내용을 미리 보세요. -f flag 뒤에는 파일명이 와야 합니다.
# create a tar archive (no compression)
tar -cf archive.tar file1.txt file2.txt
tar -cf archive.tar directory/
# extract a tar archive
tar -xf archive.tar
tar -xf archive.tar -C /target/dir/ # extract to specific directory
# list contents without extracting
tar -tf archive.tar
tar -tvf archive.tar # verbose (with details)
# verbose create/extract
tar -cvf archive.tar dir/ # show files being added
tar -xvf archive.tar # show files being extracted
# append files to existing archive
tar -rf archive.tar newfile.txt
# extract specific files
tar -xf archive.tar path/to/file.txt
tar -xf archive.tar "file*.txt"
# exclude files
tar -cf archive.tar dir/ --exclude="*.log"
tar -cf archive.tar dir/ --exclude="node_modules"
# common flags:
# c = create
# x = extract
# t = list
# f = file (specify archive name)
# v = verbose
# r = append
# u = update (only newer files)
# C = change to directory
# preserve permissions (default for root)
tar -cpf archive.tar dir/ # p = preserve permissions
# show what would be done (dry run)
tar -tf archive.tar | head -10압축이 있는 tar
tar가 flag로 여러 압축 알고리즘을 지원합니다: z(gzip), j(bzip2), J(xz), --zstd(zstd). gzip이 표준입니다(빠르고 어디에나 있음); bzip2가 더 잘 압축하지만 느리고, xz가 최고 비율이지만 가장 느리며, zstd가 현대적입니다(가장 빠르고 비율 좋음). 현대 tar는 추출 시 압축을 자동 감지하므로 -xf가 어떤 형식이든 동작합니다. 압축 수준(1-9)이 크기와 속도를 교환합니다. 백업에는 xz나 zstd를 권합니다.
# tar + gzip (most common, .tar.gz or .tgz)
tar -czf archive.tar.gz dir/ # create
tar -xzf archive.tar.gz # extract
tar -tzf archive.tar.gz # list
# tar + bzip2 (better compression, slower)
tar -cjf archive.tar.bz2 dir/ # create
tar -xjf archive.tar.bz2 # extract
tar -tjf archive.tar.bz2 # list
# tar + xz (best compression, slowest)
tar -cJf archive.tar.xz dir/ # create
tar -xJf archive.tar.xz # extract
tar -tJf archive.tar.xz # list
# tar + zstd (fast + good ratio, modern)
tar --zstd -cf archive.tar.zst dir/ # create
tar --zstd -xf archive.tar.zst # extract
# specify compression level (1-9, default 6)
GZIP=-9 tar -czf archive.tar.gz dir/ # max gzip compression
XZ_OPT=-9e tar -cJf archive.tar.xz dir/ # max xz compression
# compression comparison:
# gzip: fast, medium compression (.tar.gz)
# bzip2: medium, good compression (.tar.bz2)
# xz: slow, best compression (.tar.xz)
# zstd: fastest, good compression (.tar.zst)
# extract: tar auto-detects compression
tar -xf archive.tar.gz # works without -z flag
tar -xf archive.tar.xz # works without -J flag
# compress to stdout (for piping)
tar -cz dir/ | ssh user@host "cat > backup.tar.gz"zip & unzip
zip이 Windows에서 흔하고 널리 지원됩니다. -r이 디렉터리를 재귀하고, -e가 비밀번호로 암호화하며(프롬프트), -x가 패턴을 제외하고, -s가 여러 파트로 분할합니다(큰 파일에 유용). unzip -l이 나열하고, -d가 디렉터리로 추출하며, -t가 무결성을 검사합니다. tar+gzip과 달리 zip이 각 파일을 개별 압축해 아카이브 내 파일에 임의 접근이 가능합니다. 크로스 플랫폼 공유에는 zip이 가장 안전한 선택입니다.
# create a zip archive
zip archive.zip file1.txt file2.txt
# zip a directory recursively
zip -r archive.zip directory/
# zip with password (encryption)
zip -e -r archive.zip directory/
zip -P password archive.zip file.txt # password on command line (insecure)
# zip with specific compression level (0-9)
zip -9 -r archive.zip directory/ # maximum compression
# zip excluding files
zip -r archive.zip dir/ -x "*.log" -x "*/node_modules/*"
# split archive into parts
zip -s 100m archive.zip largefile.iso # 100MB parts
# update/add files to existing zip
zip archive.zip newfile.txt
# list contents
unzip -l archive.zip
unzip -v archive.zip # verbose with details
# extract
unzip archive.zip
unzip archive.zip -d /target/dir/
# extract specific files
unzip archive.zip file1.txt
# test archive integrity
unzip -t archive.zip
# extract to stdout
unzip -p archive.zip file.txt
# zipinfo: detailed listing
zipinfo archive.zip
zipinfo -1 archive.zip # just filenamesgzip & gunzip
gzip이 단일 파일을 압축합니다(아카이브가 아님 — 여러 파일에는 tar를 쓰세요). 원본을 .gz 파일로 교체합니다; 유지하려 -k를 쓰세요. -c가 stdout으로 출력합니다(파이핑에 유용). zcat/zless가 추출 없이 압축 파일을 읽습니다. gzip은 한 번에 하나의 파일만 다루므로 디렉터리에는 tar + gzip이 표준입니다. 압축 수준 9가 가장 작은 파일을 주지만 더 오래 걸리고, 수준 1이 가장 빠릅니다.
# compress a single file (replaces original)
gzip file.txt # creates file.txt.gz, removes file.txt
# keep the original file
gzip -k file.txt # keep original
gzip -c file.txt > file.txt.gz # alternative (to stdout)
# set compression level (1-9, default 6)
gzip -1 file.txt # fastest, least compression
gzip -9 file.txt # slowest, best compression
# decompress
gunzip file.txt.gz # creates file.txt, removes .gz
gzip -d file.txt.gz # same as gunzip
gunzip -c file.txt.gz > file.txt # keep original
gunzip -k file.txt.gz # keep original (GNU)
# compress multiple files (each gets its own .gz)
gzip file1.txt file2.txt file3.txt
# recursive (compress all files in directory)
gzip -r directory/
# test integrity
gzip -t file.txt.gz
# list compression info
gzip -l file.txt.gz
# compressed uncompressed ratio uncompressed_name
# 1234 5678 78.3% file.txt
# zcat: view compressed file without extracting
zcat file.txt.gz
zcat file.txt.gz | grep "error"
# zless: pager for compressed files
zless file.txt.gz
# concatenate and decompress
cat file1.txt.gz file2.txt.gz | gunzip > combined.txt
# compress stdin
echo "data" | gzip > data.gz
tar -cf - dir/ | gzip > archive.tar.gzxz & bzip2
bzip2가 gzip보다 잘 압축하지만 느립니다. xz(LZMA)가 최고 압축 비율이지만 가장 느립니다 — 보관에 이상적. zstd가 현대적 선택입니다: 좋은 비율로 가장 빠른 압축 해제. lz4가 극도로 빠르지만 비율이 낮습니다. 소프트웨어 배포에는 xz가 권장됩니다(가장 작은 다운로드). 실시간 압축에는 zstd나 lz4. bzcat/xzcat/zcat이 추출 없이 압축 파일을 읽습니다 — 로그 분석에 유용합니다.
# bzip2: better compression than gzip
bzip2 file.txt # compress (replaces original)
bzip2 -k file.txt # keep original
bunzip2 file.txt.bz2 # decompress
bzip2 -d file.txt.bz2 # same as bunzip2
# bzip2 compression level (1-9, default 9)
bzip2 -9 file.txt
# bzcat: view bzip2-compressed file
bzcat file.txt.bz2 | grep "pattern"
# xz: best compression ratio
xz file.txt # compress (replaces original)
xz -k file.txt # keep original
xz -d file.txt.xz # decompress
unxz file.txt.xz # same as xz -d
# xz compression level (0-9, default 6)
xz -9 file.txt # maximum compression
# xz with extreme compression (very slow)
xz -9e file.txt
# xzcat: view xz-compressed file
xzcat file.txt.xz
# zstd: fast modern compressor
zstd file.txt # compress
zstd -d file.txt.zst # decompress
zstd -19 file.txt # max compression
zstd -k file.txt # keep original
# lz4: extremely fast
lz4 file.txt # compress
lz4 -d file.txt.lz4 # decompress
# compare compression ratios
ls -lh file.txt file.txt.gz file.txt.bz2 file.txt.xz
# benchmark compression
time gzip -9 file.txt
time xz -9 file.txtSSH & 원격 접속
SSH 연결
ssh가 안전하게 원격 기기에 연결합니다. -p가 비기본 포트를 지정하고, -i가 개인 키를 고릅니다. ssh-copy-id가 비밀번호 없는 인증을 위해 공개 키를 설치합니다(비밀번호보다 훨씬 안전합니다). -v가 연결 문제(키 협상, 인증 단계) 진단에 도움됩니다. -X가 원격 GUI 앱을 위한 X11 포워딩을 켭니다. 자주 연결하는 곳은 ~/.ssh/config에 별칭으로 설정하세요.