LoginSignup
4
4

More than 5 years have passed since last update.

"Open Command" on Bash on Ubuntu on Windows

Last updated at Posted at 2017-09-09

Creators Updateにより、BashからWindowsのexeを実行できる(逆も可能)ようになりました。
そこでMacのOpenコマンドのように、「Bashから"Windows側で"ファイルを開く」コマンドを作ってみます。

Bash on Ubuntu on Windowsでopenコマンドみたいなシェルスクリプトを参考にしました

  1. 空白を含むパスへの対策
    Bashのデフォルト区切り文字はスペースのため、ファイルパスに空白が含まれると異なる複数の引数として扱われてしまう。
    例えばA B.txtというファイルを引数にopen A\ B.txtとすると$1=A$2=B.txtと分割されてしまう。
    区切り文字を別の文字に変更することで対処する(ここでは改行記号)

  2. パス変換
    ファイルがWindows上かUbuntu上かで処理を分ける。
    Windows:/mnt/c/A.txt->c:\A.txt
    Ubuntuホームディレクトリ:/home/USER/A.txt->%LocalAppData%\lxss\home\USER\A.txt
    Ubuntuシステムディレクトリの場合は危険なので開かせない。

OpenWin.sh
#!/bin/bash
IFS=$'\n'

# check number of arguments
if   [ $# -le 0 ] ; then
    echo too few arguments.
    exit 0
elif [ $# -ge 2 ] ; then
    echo too many arguments.
    exit 0
elif [ ! -e $1 ] ; then
    echo "$1" is not exist.
    exit 0
fi

absolute_path=$(readlink -f $1)

# replace
if   [[ $absolute_path =~ ^/mnt/[A-z]{1}/ ]] ; then
    # Windows mount directory
    replace_path=$(echo $absolute_path | sed -e 's|\/mnt\/\([A-z]\)|\1:|g'   -e 's|\/|\\|g')
elif [[ $absolute_path =~ ^/home/ ]] ; then
    # Ubuntu home directory
    replace_path=$(echo $absolute_path | sed -e 's|^|%LocalAppData%\\lxss|g' -e 's|\/|\\|g')
else
    # Ubuntu system directory
    echo "$1" is linux system directory.exit.
    exit 0
fi

# open
cmd.exe /c start "" "$replace_path"

exit 0

Windows上のファイルをWindows側で開く分には問題ないが、
LXSS上のファイルをWindows側で開くのは危険なのでそちらは多用しないほうがよさそう。

4
4
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
4
4