重複執行同一個命令行不在此文討論(須要討論嗎?).html
一個簡單的場景, kill
一個名爲Main
的Java
進程, 比較土的辦法是:shell
shell> jps 2817 Jps 11917 Main 2584 NettyServer > kill 11917
每次執行都要肉眼識別Main
進程的PID
, 效率低, 容易錯. 簡單的改進是這樣的:bash
shell> jps | awk '$2 ~ /Main/ {print $1}' | xargs kill
看上去不錯! 問題來了, 如果複用上面的命令行去kill
另外一個進程呢, 好比 NettyServer
?函數
在~/.bashrc
中定義一個函數jstop
:命令行
bash#.bashrc jstop() { jps | awk "\$2 ~ /$1/ {print \$1}" | xargs kill }
在source ~/.bashrc
後, 就能夠jstop NettyServer
了.code
若是隻是這樣, 就 兔養兔新破 了.htm
相似這樣一行命令的函數, 隨着積累的過程當中, 頻繁編輯~/.bashrc
挺煩的.教程
這兒提供一勞永逸的方案: 定義一個定義函數的函數, 以下:進程
sed -i '2 i func() {\n sed -i "2 i $1() {\\n $2 \\n}\\n" ~/.bashrc\n source ~/.bashrc\n}' ~/.bashrc;source ~/.bashrc
sed -i '' '2 i\ func() {\ sed -i "" "2 i\\\\\ $1() {\\\\\ $2\\\\\ }\\\\\ \\\\\ " ~/.bash_profile; source ~/.bash_profile\ }\ \ ' ~/.bashrc_profile; source ~/.bash_profile
在終端執行上面的命令行, 就能夠這樣定義jstop
了:ip
func jstop 'jps | awk "\\$2 ~ /$1/ {print \\$1}" | xargs kill'