Search code examples
bashshellexecscreensystemd

shell scripts that's ends when the caller script end


I have two scripts: /mnt/tmp/a.sh:

#!/bin/bash

echo hello >> /tmp/a.sh.log
i=0
/mnt/tmp/b.sh &

while [[ $i -lt "5" ]]
do
        echo "seconde : $i " >> /tmp/a.sh.log
        sleep 1
        i=$(($i+1))
done

and /mnt/tmp/b.sh

#!/bin/bash

echo hello >> /tmp/b.sh.log
i=0

while [[ $i -lt "10" ]]
do
        echo "seconde : $i " >> /tmp/b.sh.log
        sleep 1
        i=$(($i+1))
done

when I manually start /mnt/tmp/a.sh here are the outputs files: /tmp/a.sh.log

hello
seconde : 0
seconde : 1
seconde : 2
seconde : 3
seconde : 4

and /tmp/b.sh.log

hello
seconde : 0
seconde : 1
seconde : 2
seconde : 3
seconde : 4
seconde : 5
seconde : 6
seconde : 7
seconde : 8
seconde : 9

but when /mnt/tmp/a.sh is called during system startup, here are the outputs files:

/tmp/a.sh.log

hello
seconde : 0
seconde : 1
seconde : 2
seconde : 3
seconde : 4

and /tmp/b.sh.log hello

seconde : 0
seconde : 1
seconde : 2
seconde : 3
seconde : 4

When /mnt/tmp/a.sh ends all the scripts that were launched by it in the background (using &) ends!

the a.sh script is called at the boot by /usr/bin/custom-script:

#!/bin/bash


echo "===========================================" > /tmp/start
echo "        custom script                      " >> /tmp/start
echo "===========================================" >> /tmp/start

mount /dev/mmcblk0p1 /mnt
/mnt/tmp/a.sh

this custom-script is configured by /lib/systemd/system/custom-script.service as:

[Unit]
Description=start custom script at boot

[Service]
Type=simple
ExecStart=/bin/sh -c '/usr/bin/custom-script'

[Install]
WantedBy=multi-user.target

I am working in an SOM board imx6 using a yocto based system.

Already tried solutions:

all this versions of /mnt/tmp/a.sh gives the same problem:

using exec:

#!/bin/bash

echo hello >> /tmp/a.sh.log
i=0
(exec /mnt/tmp/b.sh )&

while [[ $i -lt "5" ]]
do
        echo "seconde : $i " >> /tmp/a.sh.log
        sleep 1
        i=$(($i+1))
done

using source:

#!/bin/bash

echo hello >> /tmp/a.sh.log
i=0
source /mnt/tmp/b.sh &

while [[ $i -lt "5" ]]
do
        echo "seconde : $i " >> /tmp/a.sh.log
        sleep 1
        i=$(($i+1))
done

using nohup:

#!/bin/bash

echo hello >> /tmp/a.sh.log
i=0
nohup /mnt/tmp/b.sh > /var/log/nohup.log & # I used /var/log/nohup.log because my system is read-only:nohup: can't open '/home/root/nohup.out': Read-only file system 

while [[ $i -lt "5" ]]
do
        echo "seconde : $i " >> /tmp/a.sh.log
        sleep 1
        i=$(($i+1))
done

Can someone help here?


Solution

  • I just resolve the problem:

    the service file for systemd of the custom-script should have type=forking not type=simple:

    /lib/systemd/system/custom-script.service

    [Unit]
    Description=start custom script at boot
    
    [Service]
    Type=forking
    ExecStart=/usr/bin/custom-script
    
    [Install]
    WantedBy=multi-user.target
    

    thank you!