LoginSignup
0
1

More than 5 years have passed since last update.

Ubuntu on Windows で Windows のフルパス名で cd する

Last updated at Posted at 2017-02-04

Ubuntu on Windows の bash で Windows のフルパスで cd できるようにしてみた

Ubuntu on Windows では Windows 側のフォルダが /mnt/ 以下に見えておるわけですが、Windows 側フォルダに一発で cd できると良いなあと思って実装してみました。

動作例はこんなカンジ。注意点としては Windows のフルパスはシングルクオートで囲む必要があること。こういうことができると Windows 側から見えているファイルを Ubuntu on Windows で処理するのが色々捗ると思うんですよねー。

image

実装

単純に考えると「パスを置換してcdする処理」をスクリプトにすればよさそうですが、実はこれではだめです。そのスクリプトは実行中のシェルの子プロセスですから、現在作業中のシェルに対しては何の効力もない。

というわけで、この処理は作業中のシェルで使う関数として書きつつ、本来の cd コマンドを alias で置き換えています。.bashrc とかに以下の内容を追加して新しいシェルを開いてもらえればよいです。

.bashrcなどへの追加内容
# 入力文字列がWindowsのフルパスの場合に Ubuntu on Windows のパスに置換する処理
__change_winpath2buwpath() {
    if [[ "$1" =~ ^([A-Za-z]):(.*) ]]; then
        # 入力文字列が Windows のフルパスならば
        # ドライブレターとディレクトリに分解する
        windows_driveletter=${BASH_REMATCH[1],}
        windows_path=${BASH_REMATCH[2]}

        # ドライブレターとパスを含めて Ubuntu on Windows 上でのパスにする
        # このときにドライブレターは小文字に変換し
        # バックスラッシュをスラッシュに置換している
        newpath="/mnt/${windows_driveletter}${windows_path//\\/\/}"
    else
        newpath="$1"
    fi
}

#
__cd() {
    if [ "$1" == "" ]; then
        # パラメータが未指定の場合は cd コマンドをパラメータ無しで実行する
        \cd
    else
        # Windowsのフルパスが含まれていたら
        # Ubuntu on Windows のパスに変換する処理
        __change_winpath2buwpath "$1"
        \cd "$newpath"
    fi
}
# cd コマンドを __cd に置換する
alias cd=__cd

参考資料

ここらへんの内容を参考にしています。

samba経由で参照中のフォルダのパスをssh経由でログイン中のシェルでcdする。
http://pslabo.hatenablog.com/entry/2016/01/27/samba%E7%B5%8C%E7%94%B1%E3%81%A7%E5%8F%82%E7%85%A7%E4%B8%AD%E3%81%AE%E3%83%95%E3%82%A9%E3%83%AB%E3%83%80%E3%81%AE%E3%83%91%E3%82%B9%E3%82%92ssh%E7%B5%8C%E7%94%B1%E3%81%A7%E3%83%AD%E3%82%B0%E3%82%A4

Bashで変数を大文字小文字変換(uppercase/lowercase)する
http://qiita.com/kawaz/items/211266021515b3f033a3

[Bash]正規表現マッチした部分文字列を再利用する方法
http://dqn.sakusakutto.jp/2013/06/bash_rematch_regexp.html

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