コマンド概要
mv コマンドは、ファイルやディレクトリの移動と名前変更を行うためのUNIX系OSの基本コマンドです。あるディレクトリから別のディレクトリへファイルを移動したり、ファイル名を変更したりできます。もし移動先に同名のファイルが既に存在する場合、そのファイルの内容は上書きされます。
移動元がファイルで移動先がディレクトリの場合、ファイルの位置が変わります。移動元がディレクトリの場合、移動先もディレクトリである必要があり、その場合はディレクトリ名の変更が行われます(ファイルへの移動は不可)。
mv コマンドの動作は、移動先の種類によって4つのパターンに分類されます:
- 移動先が特定のファイルパスである場合、移動元ファイルはそのディレクトリに元のファイル名で配置される。
- 移動先がディレクトリでない場合、移動元(1つだけ)のファイル名が移動先の名前に変更される。同名ファイルがあれば上書きされる。
- 移動元と移動先が同じディレクトリ内にある場合、
mvは単にファイル名の変更として機能する。 - 移動先がディレクトリの場合、移動元は複数指定でき、すべてのファイルがそのディレクトリに元のファイル名で移動される。
構文
mv [オプション] 移動元 移動先
mv [options] source destination
主なオプション
| オプション | 説明 |
|---|---|
-b | 移動先に同名ファイルが存在する場合、上書き前にバックアップを作成する。 |
-f | 強制上書き。移動先にファイルやディレクトリが存在しても確認せずに上書きする。 |
-i | インタラクティブモード。上書き前に確認を求め、Y/N で応答する。 |
-u | 移動先に同名ファイルが存在し、かつ移動元の方が新しい場合のみ更新する。 |
-t | 移動先ディレクトリを指定する。複数ファイルを一度に移動する場合に便利で、構文は mv -t 移動先 ファイル1 ファイル2 ... となる。 |
-S 接尾辞 | バックアップファイルの接尾辞を指定する。デフォルトは ~。 |
-n | 既存のファイルを上書きしない。 |
-T | 移動先をディレクトリではなく通常ファイルとして扱う。 |
-v | 実行過程を詳細に表示する。 |
使用例
ファイルをディレクトリに移動
[root@centos7 testdir]# ll
total 0
-rw-r--r-- 1 root root 0 Feb 25 2021 filetest
-rw-r--r-- 1 root root 0 Feb 25 2021 testfile
[root@centos7 ~]# mv mingongge.txt testdir/
[root@centos7 ~]# ll testdir/
total 0
-rw-r--r-- 1 root root 0 Feb 25 2021 filetest
-rw-r--r-- 1 root root 0 Jan 2 08:43 mingongge.txt
-rw-r--r-- 1 root root 0 Feb 25 2021 testfile
移動と名前変更を同時に実行
[root@centos7 testdir]# mv mingongge.txt test/mingongge
[root@centos7 testdir]# ll test/
total 0
-rw-r--r-- 1 root root 0 Jan 2 08:50 mingongge
上書き防止オプション -n の利用
移動先に同名ファイルが既にある場合、-n を指定すると上書きを防げます。
[root@centos7 testdir]# ll *.txt dir/*.txt
-rw-r--r-- 1 root root 0 Jan 2 08:58 dir/test1.txt
-rw-r--r-- 1 root root 0 Jan 2 08:58 dir/test2.txt
-rw-r--r-- 1 root root 0 Jan 2 09:03 test1.txt
-rw-r--r-- 1 root root 0 Jan 2 08:57 test2.txt
-rw-r--r-- 1 root root 0 Jan 2 09:03 test3.txt
[root@centos7 testdir]# mv -nv *.txt dir/
‘test3.txt’ -> ‘dir/test3.txt’
# 移動先に test3.txt が無いため、移動成功
[root@centos7 testdir]# ll
total 0
drwxr-xr-x 2 root root 57 Jan 2 09:04 dir
-rw-r--r-- 1 root root 0 Jan 2 09:03 test1.txt
-rw-r--r-- 1 root root 0 Jan 2 08:57 test2.txt
バックアップ機能の活用
移動先に同名ファイルが存在する場合、-b オプションで自動バックアップを作成できます。
[root@centos7 dir]# cat test1.txt
1
[root@centos7 dir]# cat test2.txt
2
[root@centos7 dir]# mv -b test1.txt test2.txt
mv: overwrite ‘test2.txt’? y
[root@centos7 dir]# ll
total 12
-rw-r--r-- 1 root root 2 Jan 2 09:12 test2.txt
-rw-r--r-- 1 root root 2 Jan 2 09:12 test2.txt~
-rw-r--r-- 1 root root 2 Jan 2 09:12 test3.txt
[root@centos7 dir]# cat test2.txt
1
[root@centos7 dir]# cat test2.txt~
2
バックアップ接尾辞のカスタマイズ
--suffix オプションでバックアップファイルの接尾辞を変更できます。
[root@centos7 dir]# mv -b --suffix=.bak test2.txt test3.txt
mv: overwrite ‘test3.txt’? y
[root@centos7 dir]# ll
total 12
-rw-r--r-- 1 root root 2 Jan 2 09:12 test2.txt~
-rw-r--r-- 1 root root 2 Jan 2 09:12 test3.txt
-rw-r--r-- 1 root root 2 Jan 2 09:12 test3.txt.bak
[root@centos7 dir]# cat test3.txt
1
[root@centos7 dir]# cat test3.txt.bak
3