Bash – Write PID To File On Bash Execution

bashbash-scriptingcron

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:

#!/bin/sh

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.

Best Answer

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

echo $$ >/tmp/backup_pid
Related Question