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

More than 5 years have passed since last update.

コマンドラインでバックスラッシュのパスでも移動できるようにする

0
Last updated at Posted at 2018-03-03

atomでパスをコピーした際にバックスラッシュを使ったC:\Users\みたいなパスがコピーされるので、ターミナルでディレクトリ移動する際にスラッシュのパスに置換したい。

つまりこうしたいC:\Users\C:/Users/

コード

~/.bashrc
cd2(){
  local fullPath=""
  #「:」を「:/」にする
  local x=${1/:/:/}
  for (( i = 0; i < ${#1} + 2; i++ )); do
    # 引数を先頭からfullPathに代入
    fullPath+=${x:$i:1}
    # ディレクトリが存在したら「/」を加える
    if [[ -d $fullPath ]]; then
      fullPath=$fullPath/
      dirPath=$fullPath
    fi
  done
  # 「//」を「/」に変換する、しかし「/」が複数付いてても平気みたい
  # dirPath=${dirPath/\/\//\/};
  cd "$dirPath"
}

こんな感じで使える

$ cd2 D:\documents\replace.sh

メモ

置換するだけかと思いきや「\」(バックスラッシュ)単体だと以下のように消えてしまう

$ echo D:\documents\replace.sh
D:documentsreplace.sh

なので-d フォルダパスでフォルダが存在するか確認して、ディレクトリを確認するごとに「/」(スラッシュ)を入れる

  if [[ -d $fullPath ]]; then
    fullPath=$fullPath/
    dirPath=$fullPath
  fi
0
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
0
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?