LoginSignup
1
1

More than 1 year has passed since last update.

Linux: ディレクトリ構造を維持してコピーを行う方法

Posted at

たまに必要となるのでメモ。

実施環境:
Linux
[testuser@testhost ~]$ uname -a
Linux testhost 4.18.0-147.8.1.el8_1.x86_64 #1 SMP Thu Apr 9 13:49:54 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
[testuser@testhost ~]$ echo $SHELL
/bin/bash

ファイルのコピーを行う場合、通常はファイル単体でコピーが行われます。

Linux
[testuser@testhost ~]$ cp /var/log/wtmp .
[testuser@testhost ~]$ ls -l wtmp
-rw-r--r-- 1 testuser testgrp 9216 Jul 14 13:57 wtmp

ただ、バックアップを取る時等、ファイルのディレクトリ構造ごとコピーを行いたい場合があります。
そのような時に使用するのが、--parentsオプションです。

Linux
[testuser@testhost ~]$ cp --parents /var/log/wtmp .
[testuser@testhost ~]$ ls -l var/log/wtmp
-rw-r--r-- 1 testuser testgrp 9216 Jul 14 14:01 var/log/wtmp

ただし、この場合、コピー元ファイルはきちんとフルパスで指定する必要があります。
相対パスで指定した場合、指定した部分までしかディレクトリ構造はコピーされません。

Linux
[testuser@testhost var]$ pwd
/var
[testuser@testhost var]$ cp --parents log/wtmp ~
[testuser@testhost var]$ ls -l ~/log/wtmp
-rw-r--r-- 1 testuser testgrp 9216 Jul 14 14:18 /home/testuser/log/wtmp
1
1
0

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
1
1