1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【敗北】mvコマンドは移動先が存在しないとリネームになるぞ

Posted at

はじめに

先日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

初見だと何が起こってるのかわかりませんが、先ほどの説明を読んだ後だと納得できますね。

最後まで読んでいただきありがとうございました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?