複用命令行的小技巧

重複執行同一個命令行不在此文討論(須要討論嗎?).html

背景

一個簡單的場景, kill 一個名爲MainJava 進程, 比較土的辦法是: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挺煩的.教程

這兒提供一勞永逸的方案: 定義一個定義函數的函數, 以下:進程

For Linux

sed -i '2 i func() {\n  sed -i "2 i $1() {\\n $2 \\n}\\n" ~/.bashrc\n source ~/.bashrc\n}' ~/.bashrc;source ~/.bashrc

For Mac OSX

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'

參考

相關文章
相關標籤/搜索