Oh-My-Zsh的自動安裝和功能集成

Linux和Mac系統默認的shell 都是bash,但是真正強大的shell應屬於zsh,99%兼容bash,是shell中的終極殺手,有很多bash所沒有的功能,但是zsh的初期配置太過繁瑣,流行率一直不高,直到有個叫Robby Russell的傢伙在github上開發了oh-my-zsh項目,使大家使用zsh的便捷性大大提高。


由於在公司的電腦是windows,就折騰了下cygwin,並且安裝了zsh,這樣做起維護方便很多了,而且我把autojump項目也集成一起,最後寫了一個自動安裝的腳本,可以自動從當前bash環境下安裝Oh-my-zsh, autojump並初始化zsh。目前只支持Ubuntu, Centos, Debian。


我在網上收集這這套zsh profile支持的插件有(git autojump history history-substring-search systemadmin systemd), 具體使用方案可以查看插件源代碼~.oh-my-zsh/plugins/。


autojump使用方法請看autojump的官方文檔。https://github.com/wting/autojump

history-substring-search 搜索歷史明亮非常強大,強大到令你乍舌。

systemadmin集成了很多SA常用的命令。

systemd 對於centos7以後的systemctl精簡比較智能。 


#!/bin/bash
#Author:Shanker
#set -x
#set -u

clear
echo ""
echo "#############################################################"
echo "# Automatically to  Install oh-my-zsh and initialize it     #"
echo "# Intro: https://github.com/sangrealest/shanker             #"
echo "# Author: Shanker<[email protected]>                         #"
echo "#############################################################"
echo ""


#if [ `id -u` -ne 0 ]
#then
#    echo "Need root to run is, try with sudo"
#    exit 1
#fi
function checkOs(){
    if [ -f /etc/redhat-release ]
    then
        OS="CentOS"
    elif [ ! -z "`cat /etc/issue | grep -i bian`" ]
    then
        OS="Debian"
    elif [ ! -z "`cat /etc/issue | grep -i ubuntu`" ]
    then
        OS="Ubuntu"
    else
        echo "Not supported OS"
        exit 1
    fi
} 

function installSoftware(){

if [ "$OS" == 'CentOS' ]
then
        sudo yum -y install zsh git 
else
        sudo apt-get -y install zsh git
fi

zshPath="`which zsh`"
user=$(whoami)
}
function downloadFile(){
    cd ~
    git clone https://github.com/robbyrussell/oh-my-zsh.git ~/.oh-my-zsh
    git clone https://github.com/joelthelion/autojump.git
    git clone https://github.com/sangrealest/initzsh 
}
function installAutojump(){
    cd ~/autojump
    ./install.py
cat >>~/.zshrc<<EOF
[[ -s ~/.autojump/etc/profile.d/autojump.sh ]] && source ~/.autojump/etc/profile.d/autojump.sh
autoload -U compinit && compinit -u
EOF

}

function configZsh(){
    if [ -f ".zsh_history" ]
    then
        mv .zsh_history{.,backup}
    fi
    sudo usermod -s "$zshPath" $user
    cp ~/initzsh/zshrc ~/.zshrc
   
}
function main(){
    checkOs
    installSoftware
    downloadFile
    configZsh
    installAutojump
}
main


如果是cygwin使用zsh,只需要在你的.bashrc裏面加上一行 /bin/zsh即可。

效果如圖:

wKioL1agmdPjt2SQAAItSTI7evY597.jpg


下面代碼是zshprofile裏面的部分摘選出來的,仔細閱讀你會發現,這個profile非常強大:可以補全命令參數,大小寫自動糾錯,強大的歷史命令搜索,便捷得訪問目錄,執行命令更高效,等等等等。


 

export ZSH=$HOME/.oh-my-zsh
#ZSH_THEME="ys"
plugins=(git autojump history-substring-search )
export PATH=$HOME/bin:/usr/local/bin:$PATH
source $ZSH/oh-my-zsh.sh
[[ -s /home/Shanker/.autojump/etc/profile.d/autojump.sh ]] && source /home/Shanker/.autojump/etc/profile.d/autojump.sh
autoload -U compinit && compinit -u
#color{{{
autoload colors
colors
for color in RED GREEN YELLOW BLUE MAGENTA CYAN WHITE; do
eval _$color='%{$terminfo[bold]$fg[${(L)color}]%}'
eval $color='%{$fg[${(L)color}]%}'
(( count = $count + 1 ))
done
FINISH="%{$terminfo[sgr0]%}"
#}}}
#ys theme prompt
function box_name {
    [ -f ~/.box-name ] && cat ~/.box-name || echo $HOST
}
# Directory info.
local current_dir='${PWD/#$HOME/~}'
# VCS
YS_VCS_PROMPT_PREFIX1=" %{$fg[white]%}on%{$reset_color%} "
YS_VCS_PROMPT_PREFIX2=":%{$fg[cyan]%}"
YS_VCS_PROMPT_SUFFIX="%{$reset_color%}"
YS_VCS_PROMPT_DIRTY=" %{$fg[red]%}x"
YS_VCS_PROMPT_CLEAN=" %{$fg[green]%}o"
# Git info.
local git_info='$(git_prompt_info)'
ZSH_THEME_GIT_PROMPT_PREFIX="${YS_VCS_PROMPT_PREFIX1}git${YS_VCS_PROMPT_PREFIX2}"
ZSH_THEME_GIT_PROMPT_SUFFIX="$YS_VCS_PROMPT_SUFFIX"
ZSH_THEME_GIT_PROMPT_DIRTY="$YS_VCS_PROMPT_DIRTY"
ZSH_THEME_GIT_PROMPT_CLEAN="$YS_VCS_PROMPT_CLEAN"
# HG info
local hg_info='$(ys_hg_prompt_info)'
ys_hg_prompt_info() {
        # make sure this is a hg dir
        if [ -d '.hg' ]; then
                echo -n "${YS_VCS_PROMPT_PREFIX1}hg${YS_VCS_PROMPT_PREFIX2}"
                echo -n $(hg branch 2>/dev/null)
                if [ -n "$(hg status 2>/dev/null)" ]; then
                        echo -n "$YS_VCS_PROMPT_DIRTY"
                else
                        echo -n "$YS_VCS_PROMPT_CLEAN"
                fi
                echo -n "$YS_VCS_PROMPT_SUFFIX"
        fi
}
# Prompt format: \n # USER at MACHINE in DIRECTORY on git:BRANCH STATE [TIME] \n $
PROMPT="
%{$terminfo[bold]$fg[blue]%}#%{$reset_color%} \
%{$fg[cyan]%}%n \
%{$fg[white]%}at \
%{$fg[green]%}$(box_name) \
%{$fg[white]%}in \
%{$terminfo[bold]$fg[yellow]%}${current_dir}%{$reset_color%}\
${hg_info}\
${git_info} \
%{$fg[white]%}[%*]
%{$terminfo[bold]$fg[red]%}$ %{$reset_color%}"
if [[ "$USER" == "root" ]]; then
PROMPT="
%{$terminfo[bold]$fg[blue]%}#%{$reset_color%} \
%{$bg[yellow]%}%{$fg[cyan]%}%n%{$reset_color%} \
%{$fg[white]%}at \
%{$fg[green]%}$(box_name) \
%{$fg[white]%}in \
%{$terminfo[bold]$fg[yellow]%}${current_dir}%{$reset_color%}\
${hg_info}\
${git_info} \
%{$fg[white]%}[%*]
%{$terminfo[bold]$fg[red]%}# %{$reset_color%}"
fi
#命令提示符
#RPROMPT=$(echo "$RED%D %T$FINISH")
#PROMPT=$(echo "$CYAN%n@$YELLOW%M:$GREEN%/$_YELLOW>$FINISH ")
#PROMPT=$(echo "$BLUE%M$GREEN%/
#$CYAN%n@$BLUE%M:$GREEN%/$_YELLOW>>>$FINISH ")
#標題欄、任務欄樣式{{{
case $TERM in (*xterm*|*rxvt*|(dt|k|E)term)
precmd () { print -Pn "\e]0;%n@%M//%/\a" }
preexec () { print -Pn "\e]0;%n@%M//%/\ $1\a" }
;;
esac
#}}}
#編輯器
export EDITOR=vim
#輸入法
export XMODIFIERS="@im=ibus"
export QT_MODULE=ibus
export GTK_MODULE=ibus
#關於歷史紀錄的配置 {{{
#歷史紀錄條目數量
export HISTSIZE=10000
#註銷後保存的歷史紀錄條目數量
export SAVEHIST=10000
#歷史紀錄文件
export HISTFILE=~/.zhistory
#以附加的方式寫入歷史紀錄
setopt INC_APPEND_HISTORY
#如果連續輸入的命令相同,歷史紀錄中只保留一個
setopt HIST_IGNORE_DUPS
#爲歷史紀錄中的命令添加時間戳
setopt EXTENDED_HISTORY
#啓用 cd 命令的歷史紀錄,cd -[TAB]進入歷史路徑
setopt AUTO_PUSHD
#相同的歷史路徑只保留一個
setopt PUSHD_IGNORE_DUPS
#在命令前添加空格,不將此命令添加到紀錄文件中
setopt HIST_IGNORE_SPACE
#}}}
#每個目錄使用獨立的歷史紀錄{{{
cd() {
builtin cd "$@"                             # do actual cd
fc -W                                       # write current history  file
local HISTDIR="$HOME/.zsh_history$PWD"      # use nested folders for history
if [ -f ".zsh_history" ] ; then               # if exist .zsh_history , mv
mv .zsh_history .zsh_history.backup
fi
if  [ ! -d "$HISTDIR" ] ; then          # create folder if needed
mkdir -p "$HISTDIR"
fi
export HISTFILE="$HISTDIR/zhistory"     # set new history file
touch $HISTFILE
local ohistsize=$HISTSIZE
HISTSIZE=0                              # Discard previous dir's history
HISTSIZE=$ohistsize                     # Prepare for new dir's history
fc -R                                       #read from current histfile
}
mkdir -p $HOME/.zsh_history$PWD
export HISTFILE="$HOME/.zsh_history$PWD/zhistory"
function allhistory { cat $(find $HOME/.zsh_history -name zhistory) }
function convhistory {
sort $1 | uniq |
sed 's/^:\([ 0-9]*\):[0-9]*;\(.*\)/\1::::::\2/' |
awk -F"::::::" '{ $1=strftime("%Y-%m-%d %T",$1) "|"; print }'
}
#使用 histall 命令查看全部歷史紀錄
function histall { convhistory =(allhistory) |
sed '/^.\{20\} *cd/i\\' }
#使用 hist 查看當前目錄歷史紀錄
function hist { convhistory $HISTFILE }
#全部歷史紀錄 top50
function top50 { allhistory | awk -F':[ 0-9]*:[0-9]*;' '{ $1="" ; print }' | sed 's/ /\n/g' | sed '/^$/d' | sort | uniq -c | sort -nr | head -n 50 }
#}}}
#雜項 {{{
#允許在交互模式中使用註釋  例如:
#cmd #這是註釋
setopt INTERACTIVE_COMMENTS
#啓用自動 cd,輸入目錄名回車進入目錄
#稍微有點混亂,不如 cd 補全實用
setopt AUTO_CD
#擴展路徑
#/v/c/p/p => /var/cache/pacman/pkg
setopt complete_in_word
#禁用 core dumps
#limit coredumpsize 0
#Emacs風格 鍵綁定
bindkey -e
#bindkey -v
#設置 [DEL]鍵 爲向後刪除
#bindkey "\e[3~" delete-char
#以下字符視爲單詞的一部分
WORDCHARS='*?_-[]~=&;!#$%^(){}<>'
#}}}
#自動補全功能 {{{
setopt AUTO_LIST
setopt AUTO_MENU
#開啓此選項,補全時會直接選中菜單項
setopt MENU_COMPLETE
autoload -U compinit
compinit
#自動補全緩存
zstyle ':completion::complete:*' use-cache on
zstyle ':completion::complete:*' cache-path .zcache
zstyle ':completion:*:cd:*' ignore-parents parent pwd
#自動補全選項
zstyle ':completion:*' verbose yes
zstyle ':completion:*' menu select
zstyle ':completion:*:*:default' force-list always
zstyle ':completion:*' select-prompt '%SSelect:  lines: %L  matches: %M  [%p]'
zstyle ':completion:*:match:*' original only
zstyle ':completion::prefix-1:*' completer _complete
zstyle ':completion:predict:*' completer _complete
zstyle ':completion:incremental:*' completer _complete _correct
zstyle ':completion:*' completer _complete _prefix _correct _prefix _match _approximate
#路徑補全
zstyle ':completion:*' expand 'yes'
zstyle ':completion:*' squeeze-shlashes 'yes'
zstyle ':completion::complete:*' '\\'
#彩色補全菜單
eval $(dircolors -b)
export ZLSCOLORS="${LS_COLORS}"
zmodload zsh/complist
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#)*=0=01;31'
#修正大小寫
zstyle ':completion:*' matcher-list '' 'm:{a-zA-Z}={A-Za-z}'
#錯誤校正
zstyle ':completion:*' completer _complete _match _approximate
zstyle ':completion:*:match:*' original only
zstyle ':completion:*:approximate:*' max-errors 1 numeric
#kill 命令補全
compdef pkill=kill
compdef pkill=killall
zstyle ':completion:*:*:kill:*' menu yes select
zstyle ':completion:*:*:*:*:processes' force-list always
zstyle ':completion:*:processes' command 'ps -au$USER'
#補全類型提示分組
zstyle ':completion:*:matches' group 'yes'
zstyle ':completion:*' group-name ''
zstyle ':completion:*:options' description 'yes'
zstyle ':completion:*:options' auto-description '%d'
zstyle ':completion:*:descriptions' format $'\e[01;33m -- %d --\e[0m'
zstyle ':completion:*:messages' format $'\e[01;35m -- %d --\e[0m'
zstyle ':completion:*:warnings' format $'\e[01;31m -- No Matches Found --\e[0m'
zstyle ':completion:*:corrections' format $'\e[01;32m -- %d (errors: %e) --\e[0m'
# cd ~ 補全順序
zstyle ':completion:*:-tilde-:*' group-order 'named-directories' 'path-directories' 'users' 'expand'
#}}}
##行編輯高亮模式 {{{
# Ctrl+@ 設置標記,標記和光標點之間爲 region
zle_highlight=(region:bg=magenta #選中區域
special:bold      #特殊字符
isearch:underline)#搜索時使用的關鍵字
#}}}
##空行(光標在行首)補全 "cd " {{{
user-complete(){
case $BUFFER in
"" )                       # 空行填入 "cd "
BUFFER="cd "
zle end-of-line
zle expand-or-complete
;;
"cd --" )                  # "cd --" 替換爲 "cd +"
BUFFER="cd +"
zle end-of-line
zle expand-or-complete
;;
"cd +-" )                  # "cd +-" 替換爲 "cd -"
BUFFER="cd -"
zle end-of-line
zle expand-or-complete
;;
* )
zle expand-or-complete
;;
esac
}
zle -N user-complete
bindkey "\t" user-complete
#}}}
##在命令前插入 sudo {{{
#定義功能
sudo-command-line() {
[[ -z $BUFFER ]] && zle up-history
[[ $BUFFER != sudo\ * ]] && BUFFER="sudo $BUFFER"
zle end-of-line                 #光標移動到行末
}
zle -N sudo-command-line
#定義快捷鍵爲: [Esc] [Esc]
bindkey "\e\e" sudo-command-line
#}}}


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