I need to execute a program in background, and the program should keep on running, after the shell execute. I am executing the script using nohup
and using bash -c
to make it run in background.
#!/bin/bash
cd /mnt/go/src/github.com/something && pwd && bash -c "nohup go run apps/something/main.go >> /var/logs/go/crash.log 2>&1 &"
I need to get the pid of the nohup
command executed in the spawned shell using bash -c
, I tried using
cd /mnt/go/src/github.com/something && pwd && bash -c "nohup go run
apps/something/main.go >> /var/logs/go/crash.log 2>&1 & echo $! > /var/run/something.pid"
But the output is empty string, is there any better way to solve this issue. Because of using bash -c
I cannot get the PID using $?
.
Why are you chaining everything with . Don't use &&
? If you want to stop the script if an error occurs, just add set -e
below the shebang. It makes sure that the script stops executing if a command returns an exit status not equal to 0 set -e
(read link in comments).
As I've wrongly commented in a previous edit, it seems that your code should be valid in the first place (thx @tripleee).
I think the error occurs because you use "
instead of '
. The error occurs because Bash first has to parse the string to replace variables. Since the current shell hasn't created a child process, $!
is empty and therefore your file as well. Try it with an single quote:
#! /bin/bash
cd /mnt/go/src/github.com/something
pwd
bash -c 'nohup go run apps/something/main.go >> /var/logs/go/crash.log 2>&1 & echo $! > /var/run/something.pid'
cat /var/run/something.pid
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加