adamst85
adamst85

Reputation: 197

Getting pid of script run inside of shell - $! not giving anything

I am writing a script that is runs a program using nohup that contains parameters, thus I wrap the command into a shell command. I am trying to get the pid of the program but am running into difficulties. This is what I am trying to run:

nohup bash -c '../command --dir /mnt/raid/test/test.txt  "https://www.google.com/" > temp.txt 2>&1 &'; APP_PID=$! | {
            #APP_PID=$!
            echo "the pid is ${APP_PID}"
}

The result of this script shows an empty pid as below:

the pid is

I have tried numerous variations and have searched Stack Overflow but could not find anything related.

Question is what am I doing wrong?

Upvotes: 1

Views: 196

Answers (1)

codeforester
codeforester

Reputation: 42999

The background process is being created as a grand child of your shell (by bash -c) and you won't be able to get the PID of the grand child from the outer shell. You could do this instead:

nohup bash -c '../command --dir /mnt/raid/test/test.txt  "https://www.google.com/" > temp.txt 2>&1'& APP_PID=$! && {
            echo "the pid is ${APP_PID}"
}

Here, nohup runs in background and you get its PID.

Upvotes: 1

Related Questions