LoginSignup
33
30

More than 5 years have passed since last update.

tarで圧縮する際にフルパスで保存したり、ディレクトリごと保存したりする

Last updated at Posted at 2015-10-14

昨日、なぜbasenameを取ってきたかったのかの続き。
tarでバックアップを取る時に、ディレクトリごと保存したかったので考えていました。

例えば以下のディレクトリがあるとする。

バックアップ元:/home/hoge/bin
バックアップ先:/home/hoge/backup

バックアップコマンド:/home/hoge/test.sh

こんな感じの階層

# cd /home/hoge
# ls *
test.sh

backup:

bin:
file1  file2  file3

test.shを叩くことによって、
このbinディレクトリをbin/file1bin/file2のような形で圧縮して、backupディレクトリにpiyo.tar.gzとして保存したい。

フルパスで圧縮

test.sh
#!/bin/bash
BACKUP_DIR="/home/hoge/bin"   # バックアップ元ディレクトリ
SAVE_DIR="/home/hoge/backup"  # バックアップ先ディレクトリ

tar czfP ${SAVE_DIR}/piyo.tar.gz ${BACKUP_DIR}
実行して中身を見てみる
# cd /home/hoge
# ./test.sh
# ls *
test.sh

backup:
piyo.tar.gz

bin:
file1  file2  file3
# tar ztf backup/piyo.tar.gz
/home/hoge/bin/
/home/hoge/bin/file1
/home/hoge/bin/file2
/home/hoge/bin/file3

解凍するとフルパスなので、その位置に解凍してしまって危険。
オプションPを外すと解凍した時にそのディレクトリ配下に解凍される。
tar czf ${SAVE_DIR}/piyo.tar.gz ${BACKUP_DIR}

中身を見てみる
# tar ztf backup/piyo.tar.gz
home/hoge/bin/
home/hoge/bin/file1
home/hoge/bin/file2
home/hoge/bin/file3

このままだと例えば、「home/hoge/backup」配下で解凍した時、「home/hoge/backup/home/hoge/bin/file1」…のようになって少し不便・・。

バックアップ元のカレントディレクトリ配下を圧縮

test.sh
#!/bin/bash
BACKUP_DIR="/home/hoge/bin"   # バックアップ元ディレクトリ
SAVE_DIR="/home/hoge/backup"  # バックアップ先ディレクトリ

( cd ${BACKUP_DIR} ; tar czf ${SAVE_DIR}/piyo.tar.gz . )

一番右の「.」はカレントディレクトリを指しているので、消さないこと!

実行して中身を見てみる
# cd /home/hoge
# ./test.sh
# ls *
test.sh

backup:
piyo.tar.gz

bin:
file1  file2  file3
# tar ztf backup/piyo.tar.gz
./
./file1
./file2
./file3

解凍するとその解凍したディレクトリ配下にfile1file2file3のように解凍される。

バックアップ元のカレントディレクトリごと圧縮

test.sh
#!/bin/bash
BACKUP_DIR="/home/hoge/bin"   # バックアップ元ディレクトリ
SAVE_DIR="/home/hoge/backup"  # バックアップ先ディレクトリ

( cd ${BACKUP_DIR} ; cd .. ; tar czf ${SAVE_DIR}/piyo.tar.gz `basename ${BACKUP_DIR}` )
実行して中身を見てみる
# cd /home/hoge
# ./test.sh
# ls *
test.sh

backup:
piyo.tar.gz

bin:
file1  file2  file3
# tar ztf backup/piyo.tar.gz
bin/
bin/file1
bin/file2
bin/file3

binも圧縮されている。これでうちのやりたいことは終了。
ちょっと気になるのが、わざわざcdで移動しなきゃいけないところ。

追記:

GNUのtarには-Cオプションという「オプションで指定したディレクトリに移動してからコマンドを開始する」というものがあるようで、

tar -C "$(dirname ${BACKUP_DIR})" -czf "${SAVE_DIR}/piyo.tar.gz" "$(basename ${BACKUP_DIR})"

のようにするとわざわざサブでcd移動しなくて済む!やったぜ。


変数の名前で保存元、保存先が思い浮かばなくてこうなったけどみんなどんな感じの名前を付けているんだろう。
いつもここで結構悩む。

33
30
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
30