2016-11-20 72 views
0
#function:  usage 
#description: 1. parse command line arguments 
#    2. for illegal usages, print usage message and exit 1 
#    3. otherwise, communicate to main() what flags are set 

function usage { 
while getopts ":gn:" OPT; do 
    case $OPT in 
      g) ;; 
      n) name=$OPTARG;; 
      :) echo "$USAGE" 
       exit 1 
      ;; 
      \?) echo "$USAGE" 
       exit 1 
      ;; 
      *) echo "$USAGE" 
       exit 1 
     esac 
done 


shift $(($OPTIND + 1)) 
} 

#function:  main 
#description: For Part 1: 
#    1. use usage() to parse command line arguments 
#    2. echo corresponding messages for each flag that is set 
# 
#    For Part 2: 
#    Kill processes based on the case return by `usage` 


function main { 

# TODO change the condition so that this line prints when '-g' is set 
    usage() 
if [ ! -z "g" ]; then 
    echo graceful kill is present 
fi 

# TODO change the condition so that this line prints when '-n' is set 
if [ ! -z "n" ]; then 
    echo process name is present 
fi 
main [email protected] 

這是我寫的,到目前爲止的時候,我希望能有像回波信息解析和未解析標誌和參數

./KillByName -g 24601
優美殺存在

./KillByName -g
用法:KillByName [-g] -n或KillByName [-g]

./KillByName -g -n慶典
優美殺存在
進程名存在

基本上,如果有-g,那麼就說明它是優雅殺害,並用名稱。如果有-n,那麼它表示該名稱退出並帶有一個名稱。 我發現我的腳本可以打印優雅殺人禮物或名字禮物的消息,但不能打印$ USAGE的錯誤。

BTW:這僅僅是使用的信息,查殺程序

回答

1

首先,沒有實際程序

usage() 

是不是你調用一個函數的方式,它應該已經

usage 

但與一個問題,你是不是從main傳遞任何函數的自變量usage,所以它應該已經蜜蜂ñ

usage "[email protected]" # Double quotes to prevent word splitting 

雖然期限 「優雅殺」 是一個悖論本身,你可以不喜歡

while getopts ":gn:" OPT; do 
gracekill=0; //s 
case $OPT in 
     g) gracekill=1;; 
     n) name=$OPTARG;; 
     :) echo "$USAGE" 
      exit 1 
     ;; 
     \?) echo "$USAGE" 
      exit 1 
     ;; 
     *) echo "$USAGE" 
      exit 1 
    esac 
    done 
    echo "$gracekill $name" # Mind double quotes 

那麼做到這一點:

result=$(usage "[email protected]") 
if [ ${result:0:1} -eq '1' ] 
then 
#gracefully kill the application 
kill -9 $(pgrep "${result:1}") 
else 
#ruthlessly terminate it 
kill -15 $(pgrep "${result:1}") 
fi 

更多關於${var:offset:length}形式,見[ param expansion ]

備註:我假設你將進程名稱傳遞給函數,如果你傳遞進程號碼,那麼你不需要 pgpepkill -15 $(pgrep "${result:1}")將變成kill -15 "${result:1}"等等。 Goodluck!

+0

以及如何使-g選項標誌。也就是說,仍然需要一個pid,但使用-g時,該進程會優雅地被殺掉。但是,如果-g退出但pid不存在,它會提供虛假信息? – faker

+0

我建議不要在子shell中運行'usage'函數('result = $(usage「$ @」)') - 它增加了解析其輸出的複雜性(取決於參數採用什麼形式,這可能會非常棘手),並且其中的exit 1也不會實際退出主腳本,只是子shell。國際海事組織(IMO)將腳本選項解析代碼嵌入腳本的主要部分會更清潔,並避免所有這些複雜性。 –