プログラミング

WSL bashでpowershellに絶対パスのファイルを渡して開く方法

WSL Linux bashのコマンドラインから、powershellに絶対パスのファイルを渡して開く方法について紹介します。

どうやら、WSL bashは絶対パスでファイルを開くことが苦手なようです。
cmd /cなんかだと、C:/からはじまる絶対パスでいけるんですが、Powershellだと、powershell . C:/hoge/hoge.mp4みたいにしても

こうなる。

$ psl . C:\_videos\agd\video_20180824_104256.mp4
. : The term 'C:_videosagdvideo_20180824_104256.mp4' is not recognized as the name of a cmdlet, function, script file,
or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:3
+ . C:_videosagdvideo_20180824_104256.mp4
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (C:_videosagdvideo_20180824_104256.mp4:String) [], CommandNotFoundExcept
ion
+ FullyQualifiedErrorId : CommandNotFoundException

じゃあ/mnt/パスならどうか。

$ psl . /mnt/c/_videos/agd/video_20180824_104256.mp4
. : The term '/mnt/c/_videos/agd/video_20180824_104256.mp4' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again.
At line:1 char:3
+ . /mnt/c/_videos/agd/video_20180824_104256.mp4
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (/mnt/c/_videos/...0824_104256.mp4:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

ということで、絶対パスはどうも、開けないんですよね。
いや、コマンドプロンプトで開けば、開けるんですけど…いちいち/mnt/→C:変換するのも…っていうか、最近知ったwslpathコマンドもなんかよくわかんないけど使えないし……。まぁベータなんで、そこらへんの不具合は自力で乗り切っていったほうが早い話かなぁと思います。

ということで、絶対パスは無理なので、相対パスに変換してファイルを開く、という方法をとっていきましょう。

shell – Convert absolute path into relative path given a current directory using Bash – Stack Overflowによれば、

python -c "import os.path; print os.path.relpath('[目的のファイルの絶対パス]', '[カレントパス]')"

って感じで、pythonのワンライナーで相対パスを割り出せるみたいです。rubyの expand_path('',__FILE__) でもいけそうですね。

なので、こうします。

$ python -c "import os.path; print os.path.relpath('/mnt/c/_videos/agd/video_20180824_104256.mp4', '$(echo $PWD)')"
../_videos/agd/video_20180824_104256.mp4

いい感じ。

psl . $(python -c "import os.path; print os.path.relpath('/mnt/c/_videos/agd/video_20180824_104256.mp4', '$(echo $PWD)')")

……開けました。(pslはpowershell.exeの独自エイリアス。)

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です