I'm executing a bash script via cron. I want to write the process id (PID) of the script to a /tmp/ file for reference, in case I need to kill it later on (this script can take 6 - 10 hours to complete).

Is it possible to do something like this:


echo ${PID} > /tmp/backup_pid
rest of the script

Each time the script executes tar or rsync, they are launched as independant processes, hence why I'd like this PID feature.

This answer (https://superuser.com/a/238533/314696) suggests using eval, but I've been taught that eval is evil. Thanks.


The shell variable $$ contains the PID of the current running script. You could use it like this:

echo $$ >/tmp/backup_pid

If you want to get PID:

    pgrep Process                ###Write process name instead of "Process"###

If you want to get PID and kill process from GNOME Terminal:

    pid=$(pgrep Process) && kill -9 $pid

If you want to end a task with shell scripting:

    pdi=$pgrep Process)
    kill -9 $pid

Or write PID to a file:

    pgrep Process > FileName.Format

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.