faker faker - 18 days ago 11
Linux Question

echo information when parsing and not parsing flags and argument

#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 $@


This is what I write so far, I want to have something like

./KillByName -g 24601

​graceful kill is present

or

./KillByName -g

​Usage: KillByName [-g] -n or KillByName [-g]

or

./KillByName -g -n bash

graceful kill is present

process name is present

essentially, if there is -g, then it shows it is gracefully killed, and with a name. If there is -n, then it says the name exits and with a name.
I found my script can print the message of whether graceful kill present or name present, but cannot print the mistake of $USAGE.

BTW: this is only for information of usage, not actually program of killing the program

Answer

First of all,

usage()

is not the way you call a function, It should've been

usage

But there is a problem with that, you're not passing any arguments to the function usage from main, so it should've been

usage "$@" # Double quotes to prevent word splitting

Though the term "graceful killing" is a paradox in itself, you could do something like

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  

Then do this :

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

For more on ${var:offset:length} form, see [ param expansion ]

Notes : I assume that you're passing the process names to the function, if you're passing the process number, then you don't need the pgpep ie kill -15 $( pgrep "${result:1}" ) will become kill -15 "${result:1}" and so.Goodluck!