2016-11-20 71 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)将脚本选项解析代码嵌入脚本的主要部分会更清洁,并避免所有这些复杂性。 –