Saturday, April 23, 2022

[SOLVED] How to get nohup proccess id in bash script

Issue

I have a bash script to run a command via nohup, I need the proccess id in the script.

I tried this:

#!/bin/bash
nohupResult=$((nohup mycommand > nohup.out &) 2>&1)
echo $nohupResult
exit 0

But the $nohupResult is null.

I tried also this:

nohupResult=`nohup mycommand > nohup.out &`

But the $nohupResult is null either.

If I run the command nohup mycommand > nohup.out & in shell, I will get some outputs like:

[1] 447019

But how could I get the process id in the script?

Any help would be much appreciated.


Solution

The pid of the last background job is in $!

nohup mycommand &
pid=$!


Answered By - William Pursell
Answer Checked By - Robin (WPSolving Admin)