This is a simplified example:
script1
#!/bin/bash
./script2
script2
#!/bin/bash
foo() {
parent_script=$(ps -o comm= $PPID)
echo "Parent script: $parent_script" > log
}
foo &
Contents of log (after running script1):
Parent script:
I can get around this either by making the function a non-background one or by getting the parent script name outside the function and passing it as an argument:
script2
#!/bin/bash
foo() {
echo "Parent script: $1" > log
}
parent_script=$(ps -o comm= $PPID)
foo "$parent_script" &
Contents of log (after running script1):
Parent script: script1
To make things stranger, if I just add a sleep 1 after the foo & line in the original script2, I also get the expected result:
#!/bin/bash
foo() {
parent_script=$(ps -o comm= $PPID)
echo "Parent script: $parent_script" > log
}
foo &
sleep 1
However I'd like to know 1) why does the first example not work, 2) is there a way to get the parent script name from inside the background function?
script1(I think you meantpgrep script1), not only the one which launchedscript2. There could be hundreds of them running in parallel.sleep 1after thefoo &line in script2, it works as expected! Some kind of weird race condition?sleep 1command) indashandzsh.sleep 1, I addseq 1 120000000 > /dev/nullwhich takes around a second to run on my machine. In contrast,seq 1 12000 > /dev/null, which takes around 0.004s makes no difference. So we seem to need something that takes at least a second or so after the backgrounded function in order for it to work.