I have a bash script that contains a loop over a list of subdirectories. Inside the loop I cd
into each subdirectory, run a command using nohup
and then cd
back out. In the following example I have replaced the executable by an echo
command for simplicity.
#!/bin/bash
dList=("dname1" "dname2" "dname3")
for d in $dList; do
cd $d
nohup echo $d &
cd ..
done
The above causes nohup to hang during the first loop with the following output:
$ ./script.sh
./dname1
$ nohup: appending output to `nohup.out'
The script does not continue through the loop and in order to type again on the command line one must press the enter key.
OK, this is normal nohup
behaviour when one is using it on the shell, but obviously it doesn't work for my script. How can I get nohup
to simply run and then gracefully allow the script to continue?
I have already (unsuccessfully) tried variations on the nohup command including
nohup echo $d < /dev/null &
but that didn't help. Further, I tried including
trap "" HUP
at the top of the script too, but this did not help either. Please help!
EDIT: As @anubhava correctly pointed out my loop contained an error which was causing the script to only use the first entry in the array. Here is the corrected version.
#!/bin/bash
dList=("dname1" "dname2" "dname3")
for d in ${dList[@]}; do
cd $d
nohup echo $d &
cd ..
done
So now the script achieves what I wanted. However, we still get the annoying output from nohup, which was part of my original question.
Problem is here:
for d in $dList; do
That will only run for
loop once for the 1st element of the array.
To iterate over an array use:
for d in ${dList[@]}; do
Full working script:
dList=("dname1" "dname2" "dname3")
for d in "${dList[@]}"; do
cd "$d"
{ nohup echo "$d" & cd -; } 2>/dev/null
done