はじめに
先日CIジョブを書いており、mvコマンドを使う機会がありました。
mv == move やろ?? ファイル・フォルダの移動やろ??という理解だけで挑み、一瞬ハマりかけたので、反省文を残します。
mvは、移動またはリネームを行うコマンド
manを見てみます。
$ man mv
>>>
(略)
DESCRIPTION
In its first form, the mv utility renames the file named by the source operand to the destination path named by the target operand. This form is
assumed when the last operand does not name an already existing directory.
In its second form, mv moves each file named by a source operand to a destination file in the existing directory named by the directory operand.
The destination path for each operand is the pathname produced by the concatenation of the last operand, a slash, and the final pathname component
of the named file.
(略)
なんとなく訳します。
1つ目の挙動としては、mvユーティリティはsourceオペランドで指定されたfileをtargetオペランドで指定されたpathにリネームします。この挙動は最後のオペランド(targetオペランド)が存在しないときに実行されます。
2つ目の挙動としては、mvはsourceオペランドで指定された各ファイルを、directoryオペランドで指定された、存在するディレクトリへと移動します。各オペランドの移動先パスについては、directoryオペランド/元のファイル(フォルダ)名
となります。
ちゃんと書いてありました。
つまり、「移動先のパスが存在しないとき、mvコマンドはリネームをするぞ」ということになります。
試してみる1
こんなディレクトリを用意しました。
.
├── baz
│ └── hoge.txt
└── foo
└── bar
$ mv baz/hoge.txt foo/bar
とすると、、、
.
├── baz
└── foo
└── bar
└── hoge.txt
これはいいですよね。
試してみる2
次が問題です。
.
├── baz
│ └── hoge.txt
└── foo
└── bar
このディレクトリ構造に対して、
$ mv baz/hoge.txt foo/banana
を実行するとどうなるでしょう。
先ほどの説明に照らし合わせると、foo/banana
というフォルダは存在しないので、リネームの挙動になります。
つまり、「baz/hoge.txt
というファイルをfoo/banana
というファイルにリネームする」挙動になるので、こうなります。
.
├── baz
└── foo
├── banana
└── bar
初見だと何が起こってるのかわかりませんが、先ほどの説明を読んだ後だと納得できますね。
最後まで読んでいただきありがとうございました。