shellscriptingprocess

How to set the process name of a shell script?


Is there any way to set the process name of a shell script? This is needed for killing this script with the killall command.


Solution

  • Here's a way to do it, it is a hack/workaround but it works pretty good. Feel free to tweak it to your needs, it certainly needs some checks on the symbolic link creation or using a tmp folder to avoid possible race conditions (if they are problematic in your case).

    Demonstration

    wrapper

    #!/bin/bash
    script="./dummy"
    newname="./killme"
    
    rm -iv "$newname"
    
    ln -s "$script" "$newname"
    
    exec "$newname" "$@"
    

    dummy

    #!/bin/bash
    echo "I am $0"
    echo "my params: $@"
    
    ps aux | grep bash
    
    echo "sleeping 10s... Kill me!"
    sleep 10
    

    Test it using:

    chmod +x dummy wrapper
    ./wrapper some params
    

    In another terminal, kill it using:

    killall killme
    

    Notes

    Make sure you can write in your current folder (current working directory).

    If your current command is:

    /path/to/file -q --params somefile1 somefile2
    

    Set the script variable in wrapper to /path/to/file (instead of ./dummy) and call wrapper like this:

    ./wrapper -q --params somefile1 somefile2