(O+P)ut

アウトプット



(O+P)ut

エンジニアのアウトプット

【vim】Found a swap file by the name "xx.swp"と出た場合

スポンサーリンク

事象

viにてファイルを編集する際に以下のような警告が表示される。

E325: ATTENTION
Found a swap file by the name "x.sh.swp"
          owned by: root   dated: ...
         file name: ~root/hoge/x.sh
          modified: YES
         user name: root   host name: instance-1
        process ID: 10734
While opening file "x.sh"
             dated: F...

(1) Another program may be editing the same file.  If this is the case,
    be careful not to end up with two different instances of the same
    file when making changes.  Quit, or continue with caution.
(2) An edit session for this file crashed.
    If this is the case, use ":recover" or "vim -r x.sh"
    to recover the changes (see ":help recovery").
    If you did this already, delete the swap file ".x.sh.swp"
    to avoid this message.

Swap file ".x.sh.swp" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort:

原因

同一ディレクトリ内に"ファイル名+.swp"という隠しファイルができている。

ls -al
-rw-r--r--  1 root root 12288 Jan 17 08:05 .x.sh.swp

前回にviにて編集時に、保存前にviエディタが強制終了すると上記のようなスワップファイルが作成されてしまい、元ファイルを編集しようとするとロックがかかっています。

対応策

一番ダメージが少ないと思われるのは、元ファイルをコピーしておいてリカバリーをかけるものだと思います。

要は、元ファイルを別名でコピーしておき、.swapファイルを反映させてクラッシュ直前にまで戻す方法です。

$ cp x.sh x_bk.sh

とコピーしておき、viで警告画面が出ているところで「R」を押せば

Contents
Using swap file ".x.sh.swp"
Original file "~/hoge/x.sh"
Recovery completed. You should check if everything is OK.
(You might want to write out this file under another name
and run diff with the original file to check for changes)
You may want to delete the .swp file now.

上記のように反映が完了します。

あとはdiffコマンドでそれらの差異を確認したり

$ diff x.sh x_bk.sh

不要になったswapファイルを削除すれば同事象に対応は終了です。

$ rm .x.sh.bk

以上、ご参考になれば幸いです。