backend

리눅스 아카이빙, 압축 (Linux archiving): gzip, tar ...

seul chan 2020. 12. 21. 22:33

18. Archiving and backup

  • gzip, bzip2, tar, zip, rsync

Compressing files

압축은 데이터의 과잉(redundancy)를 줄이는 것.

  • lossless: 데이터를 원본 그대로 압축하는것
  • lossy: 데이터를 제거하여 압축하는것 (JPEG, MP3 등)

GZIP

root@3c28bc830cb6:~# ls -l foo.txt
-rw-r--r-- 1 root root 3680 Dec 12 03:37 foo.txt
root@3c28bc830cb6:~# gzip foo.txt
root@3c28bc830cb6:~# ls -l foo.*
-rw-r--r-- 1 root root 821 Dec 12 03:37 foo.txt.gz
root@3c28bc830cb6:~# ls -l foo.*^C
root@3c28bc830cb6:~# gunzip foo.txt.gz
root@3c28bc830cb6:~# ls -l foo.txt
-rw-r--r-- 1 root root 3680 Dec 12 03:37 foo.txt

다양한 옵션이 있음

  • -d: --decompress, --uncompress
  • -f: --force
  • -l: --list
  • -r: --recursive
  • -t: --test. 압축 파일의 integrity를 테스트
  • -v: --vervose
# 압축 파일 테스트
$ gzip -tv foo.txt.gz
foo.txt.gz:    OK

압축 파일의 내용을 보려면 여러가지 명령어로 가능

# standard output
$ gunzip -c foo.txt | less

# gunzip -c와 동일한 zcat도 있음
$ zcat foo.txt.gz | less

# zcat | less와 동일한 zless도 있음
$ zless too.txt.gz

bzip도 리눅스에서는 많이 쓰인다.

root@3c28bc830cb6:~# ls -l /etc > foo.txt
root@3c28bc830cb6:~# ls -l foo.txt
-rw-r--r-- 1 root root 3680 Dec 12 03:47 foo.txt
root@3c28bc830cb6:~# bzip2 foo.txt
root@3c28bc830cb6:~# ls -l foo.txt.bz2
-rw-r--r-- 1 root root 869 Dec 12 03:47 foo.txt.bz2
root@3c28bc830cb6:~# bunzip2 foo.txt.bz2

Archiving files

압축과 많이 쓰이는 방식은 archiving: 많은 파일을 모아서 하나의 큰 파일로 번들링하는 프로세스

tar

예전에 백업 테이프를 만들 때 쓰이는 tape archive의 줄임말인 tar가 많이 쓰인다.

일반 아카이빙인 .tar와 압축된 아카이브인 .tgz extension이 쓰인다.

tar mode[options] pathname...

모드는 4가지가 있다.

  • c: Create an archive. 아카이브 생성
  • x: Extract an archive. 아카이브 추출
  • r: append to the end of an archive. 아카이브의 맨 끝에 추가
  • t: list the contents of an archive. 아카이브 리스팅

tar는 옵션 사용법이 조금 특이하다. (모드 뒤에 연달아 붙이는 방식)

$ mkdir -p playground/dir-{001..100}
$ touch playground/dir-{001..100}/file-{A..Z}

# 전체 디렉토리를 아카이빙
$ tar cf playground.tar playground

c 모드 (생성 모드)에 f옵션 (이름 부여)을 주고 playground.tar를 만들었다.

# 해당 파일 리스팅
$ tar tf playground.tar

# verbose option (상세내용) 리스팅
$ tar tvf playground.tar

이제 x option으로 extract 해보자.

$ tar xf playground.tar
$ ls
playground

tar의 기본 pathname은 절대 경로가 아니라 상대경로를 사용한다.

tar는 보통 아카이브 할 파일을 찾기 위해 find와 함께 사용된다.

# 기존 playground.tar에 file-A 파일을 찾아서 append
$ find playground -name 'file-A' -exec tar rf playground.tar '{}' '+'

뿐만 아니라 standard input, output으로도 사용 가능하다

file-A를 찾아서 아카이빙, 압축하여 playground.tgz로 만드는 명령어

$ find playground -name 'file-A' | tar cf - --files-from=- | gzip > playground.tgz

-는 standard input이나 output을 지칭한다. (대부분의 프로그램에서도 그럼)

위의 명령어를 더 쉽게 사용하기 위해 tar는 z (gzip)와 j(bzip2) 옵션을 제공한다.

$ find playground -name 'file-A' | tar czf playground.tgz -T -

-T 옵션은 --files-from과 동일하다. 위 예시에서는 standard input으로 들어온 내용인 -를 사용

또 자주 사용되는 방식은 네트워크간에 파일을 주고받을 때.

# remote-sys 서버에 접속하여 Documents 디렉토리를 아카이빙한 뒤 현재 로컬 클라어인트에 다시 추출
$ ssh remote-sys 'tar cf - Documents' | tar xf -