cpコマンドについて
ファイルやディレクトリのコピーをする際に使用するコマンドです。
構文はcp コピー元 コピー先
となります。よく使うパターンだけ記載しておきます。使わないと、たまに忘れてしまうので、、
下記で試しに、ファイルのコピーを行いました。
[root@localhost tmp]# touch test.txt
[root@localhost tmp]# ll
合計 0
-rw-r--r--. 1 root root 0 10月 24 23:01 test.txt
[root@localhost tmp]# cp test.txt test.txt.bk
[root@localhost tmp]# ll
合計 0
-rw-r--r--. 1 root root 0 10月 24 23:01 test.txt
-rw-r--r--. 1 root root 0 10月 24 23:01 test.txt.bk
コピー先にディレクトリを指定した場合は、指定したディレクトリ内にファイル名をそのままでコピーする事も出来ます。まとめてファイルをコピーして、どこかに置いときたい時に使ってます。
[root@localhost tmp]# touch test_{01..05}.txt
[root@localhost tmp]# ll
合計 0
drwxr-xr-x. 2 root root 6 10月 24 23:20 test
-rw-r--r--. 1 root root 0 10月 24 23:25 test_01.txt
-rw-r--r--. 1 root root 0 10月 24 23:25 test_02.txt
-rw-r--r--. 1 root root 0 10月 24 23:25 test_03.txt
-rw-r--r--. 1 root root 0 10月 24 23:25 test_04.txt
-rw-r--r--. 1 root root 0 10月 24 23:25 test_05.txt
[root@localhost tmp]# cp test_*.txt test
[root@localhost tmp]# ll test
合計 0
-rw-r--r--. 1 root root 0 10月 24 23:26 test_01.txt
-rw-r--r--. 1 root root 0 10月 24 23:26 test_02.txt
-rw-r--r--. 1 root root 0 10月 24 23:26 test_03.txt
-rw-r--r--. 1 root root 0 10月 24 23:26 test_04.txt
-rw-r--r--. 1 root root 0 10月 24 23:26 test_05.txt
ディレクトリをコピーしたい場合は、-rオプション
を使用します。ディレクトリを再帰的にコピーするオプションです。
[root@localhost tmp]# ll | grep '^d'
drwxr-xr-x. 2 root root 101 10月 24 23:26 test
[root@localhost tmp]# cp -r test test2
[root@localhost tmp]# ll | grep '^d'
drwxr-xr-x. 2 root root 101 10月 24 23:26 test
drwxr-xr-x. 2 root root 101 10月 24 23:35 test2
後は、-pオプション
もよく使います。mode,ownership,timestampsを保持したまま、コピーを行えます。
これはrootでやらないと、所有者・所有グループがcpコマンドを実行したユーザーに書き換わってしまうのでその点は注意が必要です。
[root@localhost ~]# ll /tmp
合計 4
-rw-rw-r--. 1 test_01 test_01 5 10月 25 22:17 test_file.txt
[root@localhost ~]# cp -p /tmp/test_file.txt .
[root@localhost ~]# ll
合計 4
-rw-rw-r--. 1 test_01 test_01 5 10月 25 22:17 test_file.txt
mvコマンドについて
ファイル名の変更やファイル/ディレクトリの移動で使うコマンドです。
ファイル名の変更を行う場合はmv 対象ファイル 変更後のファイル名
で、ファイル/ディレクトリの移動はmv 対象ファイル/ディレクトリ 移動先
です。
試しにファイル名の変更をします。
[root@localhost tmp]# touch test.txt
[root@localhost tmp]# ls
test.txt
[root@localhost tmp]# mv test.txt nyao.txt
[root@localhost tmp]# ls
nyao.txt
ファイル/ディレクトリの移動も試しにやります。よく使うオプションとしては、上書き防止で-iオプション
を使用します。(cpコマンドにも同じオプションあります。)
[root@localhost tmp]# touch test_file.txt
[root@localhost tmp]# mkdir test_dir1 test_dir2
[root@localhost tmp]# mv test_file.txt test_dir1
[root@localhost tmp]# ls
test_dir1 test_dir2
[root@localhost tmp]# ls test_dir1
test_file.txt
[root@localhost tmp]# touch test_file.txt
[root@localhost tmp]# ls
test_dir1 test_dir2 test_file.txt
[root@localhost tmp]# ls test_dir1
test_file.txt
[root@localhost tmp]# mv -i test_file.txt test_dir1
mv: `test_dir1/test_file.txt' を上書きしますか? y
[root@localhost tmp]# ls
test_dir1 test_dir2
[root@localhost tmp]# mv test_dir1 test_dir2
[root@localhost tmp]# ls
test_dir2
[root@localhost tmp]# ls test_dir2/
test_dir1
終わり
コマンド使わないと忘れるので、たまに用もなくぽちぽちしてます。