#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 $@
这就是我写的,我想
./KillByName-g 24601
优雅的杀戮
或
./KillByName-g
用法:KillByName[-g]-n或KillByName[-g]
或
./KillByName-g-n巴什
优雅的杀戮
存在进程名
从本质上讲,如果存在-g,则表明它被优雅地杀死了,并且有一个名字。如果有-n,那么它表示名称退出并以名称命名。
我发现我的脚本可以打印优雅的kill present或name present的消息,但不能打印$USAGE的错误。
顺便说一句:这只是为了提供使用信息,而不是真正的程序终止程序
最佳答案
首先,
usage()
不是你调用函数的方式,应该是
usage
但是有一个问题,您没有将任何参数从
usage
传递给函数main
,所以它应该usage "$@" # 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 "$@")
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 ]注意:我假设您将进程名传递给函数,如果传递的是进程号,则不需要
pgpep
iekill -15 $( pgrep "${result:1}" )
将变成kill -15 "${result:1}"
等等。祝你好运!