Linux/Bash 치트시트
시스템 관리, DevOps, 일상 터미널 작업에 필요한 핵심 Linux 명령어 모음입니다.
파일 & 디렉토리
8 itemsls -la
숨김 파일 포함 상세 목록 보기
ls -la /var/log ls -lah --sort=size # sort by size, human-readable
cd
디렉토리 이동
cd /var/log # absolute path cd ../config # relative path cd ~ # home directory cd - # previous directory
mkdir -p
중간 디렉토리 포함 생성
mkdir -p /opt/app/{config,logs,data}
mkdir -p src/{components,utils,hooks}cp -r
파일/디렉토리 복사 (재귀적)
cp file.txt backup.txt cp -r src/ src_backup/ cp -a /var/www/ /backup/www/ # preserve permissions & timestamps
mv
파일 이동 또는 이름 변경
mv old_name.txt new_name.txt # rename mv *.log /var/log/archive/ # move multiple files mv -i file.txt /dest/ # prompt before overwrite
rm -rf
파일/디렉토리 강제 삭제
rm file.txt rm -rf /tmp/build_* rm -i important.txt # interactive (confirm before delete)
find
파일/디렉토리 검색
find /var/log -name "*.log" -mtime -7 find . -type f -size +100M find . -name "*.tmp" -delete find . -type f -name "*.js" ! -path "*/node_modules/*"
ln -s
심볼릭 링크 생성
ln -s /opt/app/current /opt/app/v2.1.0 ln -sf /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/
파일 내용
8 itemscat
파일 내용 출력
cat /etc/hostname cat -n script.sh # with line numbers cat file1.txt file2.txt > merged.txt
head / tail
파일 처음/끝 부분 보기
head -20 access.log # first 20 lines tail -50 error.log # last 50 lines tail -f /var/log/syslog # follow in real-time
grep -r
패턴으로 텍스트 검색
grep -r "ERROR" /var/log/ grep -rn "TODO" src/ # with line numbers grep -ri "password" . --include="*.env" grep -v "^#" config.ini # exclude comment lines
wc
라인/단어/바이트 수 세기
wc -l access.log # line count find . -name "*.py" | wc -l # count Python files cat README.md | wc -w # word count
sort / uniq
정렬 및 중복 제거
sort access.log | uniq -c | sort -rn | head -20 cut -d":" -f1 /etc/passwd | sort
less
대용량 파일 페이지 단위 보기
less /var/log/syslog # /pattern search forward # ?pattern search backward # n/N next/prev match # q quit
cut
텍스트에서 열 추출
cut -d":" -f1,3 /etc/passwd # fields 1 and 3 cut -d"," -f2-4 data.csv # fields 2 to 4 echo "hello world" | cut -c1-5 # first 5 characters
awk (basic)
패턴 기반 텍스트 처리
awk '{print $1, $4}' access.log # print columns 1 and 4
awk -F":" '{print $1}' /etc/passwd # custom delimiter
df -h | awk '$5 > 80 {print $6, $5}' # disks over 80%권한 & 소유권
5 itemschmod
파일 권한 변경
chmod 755 deploy.sh # rwxr-xr-x chmod 644 config.yml # rw-r--r-- chmod +x script.sh # add execute chmod -R 750 /opt/app/ # recursive
chown
파일 소유자 변경
chown www-data:www-data /var/www/html/ chown -R deploy:deploy /opt/app/ chown root:docker /var/run/docker.sock
umask
기본 파일 권한 마스크 설정
umask # show current mask umask 022 # new files: 644, dirs: 755 umask 077 # new files: 600, dirs: 700 (strict)
sudo / su
관리자 권한 실행
sudo apt update sudo -u postgres psql # run as another user sudo !! # re-run last command as root su - deploy # switch to user with login shell
chgrp
파일 그룹 변경
chgrp developers /shared/project/ chgrp -R www-data /var/www/
프로세스 관리
6 itemsps aux
실행 중인 프로세스 목록
ps aux | grep nginx ps aux --sort=-%mem | head -10 # top 10 by memory ps -eo pid,ppid,%cpu,%mem,cmd --sort=-%cpu | head
top / htop
실시간 시스템 모니터링
top -o %MEM # sort by memory htop # interactive (install: apt install htop) top -bn1 | head -20 # batch mode, non-interactive
kill / pkill
프로세스 종료
kill 12345 # graceful SIGTERM kill -9 12345 # force SIGKILL pkill -f "node server.js" # kill by command pattern killall nginx # kill all by name
nohup / &
백그라운드 실행 (터미널 종료 후에도 유지)
nohup python train.py > output.log 2>&1 & nohup ./long_task.sh & disown %1 # detach job from terminal
bg / fg / jobs
작업 제어 (백그라운드/포그라운드)
# Ctrl+Z to suspend current process jobs # list jobs bg %1 # resume job 1 in background fg %1 # bring job 1 to foreground
systemctl
시스템 서비스 관리 (systemd)
systemctl status nginx systemctl restart nginx systemctl enable --now docker # enable + start journalctl -u nginx -f # follow service logs
네트워킹
6 itemscurl
HTTP 요청 전송
curl -s https://api.example.com/status | jq .
curl -X POST -H "Content-Type: application/json" \
-d '{"key":"value"}' https://api.example.com/data
curl -o file.zip https://example.com/file.zip
curl -I https://example.com # headers onlyssh / scp
원격 서버 접속 및 파일 전송
ssh user@192.168.1.100 ssh -i ~/.ssh/key.pem ec2-user@host scp file.txt user@host:/tmp/ scp -r user@host:/var/log/ ./logs/
ss / netstat
네트워크 연결 및 포트 확인
ss -tlnp # TCP listening ports ss -tunap | grep :3000 # who is using port 3000 netstat -tlnp # (legacy) listening ports
ping / dig
네트워크 연결 확인 및 DNS 조회
ping -c 4 google.com dig example.com A # A record dig +short example.com # short output nslookup example.com
wget
파일 다운로드
wget https://example.com/file.tar.gz wget -q -O - https://get.docker.com | sh wget -r -np https://example.com/docs/
ip addr / ifconfig
네트워크 인터페이스 정보
ip addr show ip route show # routing table ip -4 addr show eth0 # IPv4 only hostname -I # all IP addresses
디스크 & 시스템
6 itemsdf -h
디스크 사용량 (파티션별)
df -h df -h / # root partition only df -hT # include filesystem type
du -sh
디렉토리/파일 크기 확인
du -sh /var/log/* du -sh * | sort -rh | head -10 # largest items du -sh --max-depth=1 /home/
free -h
메모리 사용량 확인
free -h watch -n 2 free -h # monitor every 2 seconds
uname -a / uptime
시스템 정보 확인
uname -a # kernel version uptime # how long running lsb_release -a # distro info cat /etc/os-release # OS details
lsblk / mount
블록 디바이스 및 마운트 정보
lsblk # list block devices lsblk -f # with filesystem info mount | grep /dev/sd sudo mount /dev/sdb1 /mnt/usb
dmesg / journalctl
커널 및 시스템 로그 확인
dmesg | tail -20 journalctl -xe # recent errors journalctl --since "1 hour ago" journalctl -u docker -f # follow docker logs
텍스트 처리
6 itemssed
스트림 편집기 (찾기/바꾸기)
sed 's/old/new/g' file.txt # replace all sed -i 's/localhost/0.0.0.0/g' config # in-place edit sed -n '10,20p' file.txt # print lines 10-20 sed '/^#/d' config.ini # delete comment lines
awk (advanced)
고급 텍스트 분석 및 리포트
# Sum a column
awk '{sum+=$1} END {print sum}' numbers.txt
# Print lines where field > threshold
awk -F"," '$3 > 1000 {print $1, $3}' sales.csv
# Count occurrences
awk '{count[$1]++} END {for(k in count) print k, count[k]}' log.txttr
문자 변환/삭제
echo "Hello World" | tr '[:upper:]' '[:lower:]' echo "hello:world" | tr ':' '\n' cat file.txt | tr -d '\r' # remove carriage returns cat file.txt | tr -s ' ' # squeeze repeated spaces
xargs
표준 입력을 명령어 인자로 변환
find . -name "*.log" | xargs rm cat urls.txt | xargs -n1 curl -sO find . -name "*.py" | xargs grep "import os" echo "a b c" | xargs -n1 echo # one per line
tee
출력을 화면과 파일에 동시 기록
echo "deploy started" | tee deploy.log command 2>&1 | tee -a output.log # append mode
diff / patch
파일 비교 및 패치 적용
diff -u old.conf new.conf > changes.patch patch < changes.patch diff -rq dir1/ dir2/ # compare directories
압축 & 아카이브
5 itemstar -czf (create)
tar.gz 아카이브 생성
tar -czf backup.tar.gz /opt/app/ tar -czf logs-$(date +%Y%m%d).tar.gz /var/log/*.log tar -cjf archive.tar.bz2 src/ # bzip2 (higher compression)
tar -xzf (extract)
tar.gz 아카이브 풀기
tar -xzf backup.tar.gz tar -xzf backup.tar.gz -C /opt/restore/ tar -tzf backup.tar.gz # list contents only
zip / unzip
ZIP 아카이브 생성/해제
zip -r project.zip src/ docs/ zip -e secure.zip secret.txt # encrypted unzip project.zip -d /opt/project/
gzip / zcat
개별 파일 gzip 압축/조회
gzip access.log # creates access.log.gz gunzip access.log.gz # decompress zcat access.log.gz | grep "ERROR" # read without extracting
rsync
증분 파일 동기화 (로컬/원격)
rsync -avz src/ dest/ rsync -avz --delete /opt/app/ user@host:/opt/app/ rsync -avz --exclude="node_modules" . remote:/project/
Linux/Bash 치트시트 사용 가이드
Linux는 서버, 클라우드, DevOps 환경의 표준 운영체제입니다. 이 치트시트는 파일 관리, 프로세스 제어, 네트워킹, 텍스트 처리 등 일상적인 터미널 작업에 필요한 핵심 명령어를 정리한 빠른 참조 가이드입니다.
초보자를 위한 팁
man 명령어로 매뉴얼을 확인하세요 (예: man grep). Tab 키로 자동 완성, 화살표 위/아래로 이전 명령어를 불러올 수 있습니다. Ctrl+R로 명령어 히스토리를 검색할 수 있습니다.
파이프와 리다이렉션
파이프(|)는 한 명령어의 출력을 다른 명령어의 입력으로 전달합니다. >는 출력을 파일로 저장하고, >>는 파일 끝에 추가합니다. 2>&1은 에러 출력을 표준 출력과 합칩니다.
파일 권한 이해하기
rwxr-xr-x(755)는 소유자=읽기+쓰기+실행, 그룹=읽기+실행, 기타=읽기+실행을 의미합니다. 첫 번째 자리 r=4, w=2, x=1을 더해서 숫자 표기합니다. 스크립트 실행 시 chmod +x를 잊지 마세요.