您的位置:首页 > 运维架构 > Shell

bash环境下自动安装并初始化oh-my-zsh & autojump zsh

2016-01-21 15:24 549 查看
Linux和Mac系统默认的shell 都是bash,但是真正强大的shell应属于zsh,而且完全兼容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
clearhacker

echo ""
echo "#############################################################"
echo "# Automatically to  Install oh-my-zsh and initialize it     #"
echo "# Intro: https://github.com/sangrealest/shanker             #"
echo "# Author: Shanker<shanker@yeah.net>                         #"
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`"
}
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 chsh -s "$zshPath"
cp ~/initzsh/zshrc ~/.zshrc
}
function main(){
checkOs
installSoftware
downloadFile
configZsh
installAutojump
}
main
如果是cygwin使用zsh,只需要在你的.bashrc里面加上一行 /bin/zsh即可。
效果如图:




下面代码是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
#}}}


本文出自 “天涯海阁” 博客,请务必保留此出处http://shanker.blog.51cto.com/1189689/1737213
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: