2

I need to write a bash program which will take the name of a program and a name of a signal as arguments and then do some things. If the name of the signal is not given, the default signal should be SIGINT.

The program file.sh needs to check whether the given program (from the argument) has only one process. In that case it sends the given signal to that process. If there are more processes, the file.sh just needs to print their PID numbers. In case there is no process at all, just warn the user. I guess grep and wc commands will be useful for this.

The example, should be something like

$ vi & vi &
$ bash file.sh vi SIGINT
vi: 233, 234
$ killall -s KILL vi
$ bash file.sh vi SIGINT
vi: there is no process with that name

I wrote this but it's not suitable with the example that is given above

#!/bin/bash
if [ $# -eq 0 ]; then
    echo "No arguments supplied";
elif [ $# -eq 1 ]; then
    num=$(pgrep -c $1);
    echo $num "(the default signal should be used)";
    if [ $num -gt 1 ]; then 
        pidof $1
    elif [ $num -lt 1 ]; then
        echo "Warning: the program doesn't have any processes";
    else
        echo $num and default signal is sigint
        pr=$(pidof $1)
        kill -SIGINT $pr
    fi
else
    echo "(the given signal should be sent to the program)"
fi

Any help for this would be really appreciated.

1

This one should do what you expect

#!/usr/bin/env bash
if [ $# -eq 0 ]; then
    echo "No arguments supplied";
else # at least the process name was passed ($1)
    num=$(pgrep -c -x "$1");
    if [ "$num" -gt 1 ]; then # more than one process found
        pidof "$1"
    elif [ "$num" -lt 1 ]; then
        echo "Warning: the program doesn't have any processes";
    else
        signal=SIGINT # default signal
        if [ $# -ge 2 ]; then # signal provided, use it
            signal=$2
        fi

        pr=$(pidof "$1")
        kill -"$signal" "$pr"
    fi
fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.