Shell, zsh, oh-my-zsh and theme

Dosmanthus
5 min readApr 21, 2017

--

改善你的開發環境

Shell

shell是作業系統的指令解譯器,主要的 shell 有bashzsh 。和終端模擬器不同,終端模擬器是指一個操作終端的客戶端, Mac 和 Linux 的 terminal 就是一個終端模擬器。

更換終端模擬器

雖然terminal已經很好用了,但有一個更好用的終端模擬器 iterm2

iterm2的優點:

  • 可以個人化
  • 介面比較美
  • 可以分割畫面
  • autocomplete…

使用 zsh

zsh的優點

  • 自動補全功能
  • 刪掉處理程序
# 傳統做法
$ ps -Af | grep ruby
$ kill -9 id
#使用zsh
$ kill ruby<TAB>
#持續按TAB會在列表中切換
  • 批次重新命名
$ autoload -U zmv
# zmv 是一個zsh模組,需要先載入。
$ zmv '(*).txt' '$1.html'
# 將1.txt 2.txt...改爲1.html 2.html

安裝zsh

$ apt-get install zsh
# or by homebrew
$ brew install zsh

zsh 的懶人包: oh-my-zsh

oh-my-zsh會先幫你載入一些主題、外掛跟設定,推薦安裝。

在iterm2中輸入指令安裝:

$ sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"

切換到zsh

$ chsh -s $(which zsh)

修改默認的shell時,可能會遇到錯誤:

$ chsh: /usr/local/bin/zsh: non-standard shell

將 /usr/local/bin/zsh 加入 /etc/shells 文件中即可解決。

啓用 plugins

oh-my-zsh 的 wiki 上有介紹各 plugin 的功能,要使用plugin需在 ~/.zshrc 修改:

plugins=(git osx) # 填入你想使用的plugins

推薦使用 autojump

autojump是一個命令行工具,不管你現在在什麼目錄下,它都可以讓你直接跳轉到你指定的目錄。

# 先透過 homebrew 安裝 autojump
$ brew install autojump
# 修改 ~/.zshrc 檔
plugins=(git osx autojump)

使用 j project_name 指令快速切換到指定專案,如果找不到,可以加上路徑 j path/project_name ,另外,可以利用 j --stat 檢視目前已經儲存的目錄以及加權。

更換 themes

可至下方連結選擇自己喜歡的主題:

這邊將使用agnoster theme,首先將ZSH_THEME=後面改爲agnoster

ZSH_THEME="agnoster" # 可換成你想要的主題

安裝 agnoster 需要的字形 powerline,下載解壓縮後執行 install.sh 檔。

調整設定

將顯示名稱改爲指定的名稱,在 ~/.zshrc 檔案加上:

DEFAULT_USER="YOURNAME"# 中文設定的話要加上這兩行
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

設定完成後會發現路徑有可能很長,這裏做一些調整,修改agnoster.zsh-theme:

# prompt_context的部分,只顯示使用者名稱,並改爲藍色。prompt_context() {  if [ $DEFAULT_USER ]; then    prompt_segment blue 7 "%(!.%{%F{yellow}%}.)$DEFAULT_USER"  elif [[ "$USER" != "$DEFAULT_USER" || -n "$SSH_CLIENT" ]]; then    prompt_segment blue 7 "%(!.%{%F{yellow}%}.)$USER@%m"  fi}# prompt_dir的部分改爲只顯示資料夾名稱,及更改顏色。prompt_dir() {  prompt_segment 7 black '%c'}# prompt_git() 裡更改顏色,有更動時爲紅色,反之黃色。if [[ -n $dirty ]]; then  prompt_segment red blackelse  prompt_segment yellow blackfi

修改結果:

外加:讓 iterm2 執行 VSCode

將下面程式加入 ~/.zshrc 中

function code {  
if [[ $# = 0 ]]
then
open -a "Visual Studio Code"
else
local argPath="$1"
[[ $1 = /* ]] && argPath="$1" || argPath="$PWD/${1#./}"
open -a "Visual Studio Code" "$argPath"
fi
}

$ source ~/.zshrc 後就可以在iterm2執行:

code -- 打開 VSCode
code . -- 在 VSCode 打開目前目錄
code somefile -- 在 VSCode 打開某個檔案

參考:

  • 「還在寫PHP?大師才用輕量級Ruby、JavaScript開發Web」- 邱俊濤 / 佳魁資訊

--

--

No responses yet