shell終端多目錄間快速cd工具

1.解決的問題

當在多個目錄間cd的時候,需要輸入一大串的路徑。例如在不同的項目、不同的分支代碼目錄跳轉,在桌面和文檔目錄跳轉
cd ~/Desktop/project_trunk
cd ~/Download/cang_lao_shi
cd ~/code/branch-1.11/
cd ~/code/branch-3.1/project/android 
這個工具就能令這些cd簡化成幾個字符:
g2t
g2c
g21
g2a


2.腳本配置

工具是個shell腳本,附在本文末尾,複製整個代碼保存爲任意文件名,例如g2.sh,然後在~/.bashrc的最後一行加入單引號裏的內容 'source g2.sh' 或 '. g2.sh'

3.自定義路徑

如果想加入自定義的路徑,找到

shortcut_and_paths=(xxxxx)
的地方,增加一行就可以了。每行就是一個參數和實際命令。可以看到
shortcut_and_paths=(
  'd ~/Desktop'
  's ~/Downloads/subversion-1.7.17'
  '7 ~/Downloads/gmock-1.7.0'
  'n ~/Documents/department/17無線推广部/內部文檔/主管文檔'
  'wk /home/liuhx/Desktop/WebKit/Source/WTF/icu'
)
第一個空格前是g2的後綴,第一個空格後是cd的路徑。增加完需要重新source或者新建一個terminal纔會生效。

如果忘了可以g2啥,可以輸入g2help(不是g2hell哦)就能列出所有命令。


附腳本:

#!/bin/bash
#author http://blog.csdn.net/hursing

# this variable should be complex enough to avoid naming pollution
shortcut_and_paths=(
  'd ~/Desktop'
  's ~/Downloads/subversion-1.7.17'
  '7 ~/Downloads/gmock-1.7.0'
  'n ~/Documents/department/17無線推广部/內部文檔/主管文檔'
  'wk /home/liuhx/Desktop/WebKit/Source/WTF/icu'
)

for ((i = 0; i < ${#shortcut_and_paths[@]}; i++)); do
  cmd=${shortcut_and_paths[$i]}
  shortcut=${cmd%% *}
  path=${cmd#* }
  func="g2$shortcut() { cd $path; }"
  eval $func
done

g2help() {
  for ((i = 0; i < ${#shortcut_and_paths[@]}; i++)); do
    cmd=${shortcut_and_paths[$i]}
    shortcut=${cmd%% *}
    path=${cmd#* }
    echo -e "g2$shortcut\t=>\tcd $path"
  done
  echo -e "\033[0;33;1mexample: input 'g2${shortcut_and_paths[0]%% *}' to run 'cd ${shortcut_and_paths[0]#* }'\033[0m"
}

FAQ:

爲什麼不用alias呢?因爲非交互式shell不會展開alias,也就是用function就能被其它腳本調用了

轉載請註明出處:http://blog.csdn.net/hursing

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章