I have tried some suggestions I saw on similar posts, but my script is not exiting after it completes. I have to hit enter for it to exit. Its running a function called foo, and its running okay. But when it finishes its just writing Done $i where i is the last item, and then just space, I have to hit enter to exit. Thank you in advance.
#!/bin/bash
PATH=/opt/conda/bin:$PATH
export PATH
eval "$(conda shell.bash hook)"
conda activate prokka_env &&
foo () {
local i=$1
prokka $i --outdir ./"${i%.*}" --prefix "${i%.*}"
echo Done $i
}
for i in *.fasta; do foo "$i" & done
CodePudding user response:
Firstly, I assume you meant to use &
after conda activate prokka_env
instead of &&
(though it may be better to not run that command in the background).
Secondly, since you run all your foo
s in the background with &
, you need to add wait
at the end of your script so that your script will end automatically once all background tasks have finished running.
For more info on wait
see its entry in the GNU bash manual or run help wait
.
CodePudding user response:
Thank you, adding wait did the trick. This is the final code in case someone else finds it useful.
#!/bin/bash
PATH=/opt/conda/bin:$PATH
export PATH
eval "$(conda shell.bash hook)"
conda activate prokka_env
foo () {
local i=$1
prokka $i --outdir ./"${i%.*}" --prefix "${i%.*}"
echo Done $i
}
for i in *.fasta; do foo "$i" & done
wait
echo "All jobs completed."
CodePudding user response:
I think what's really happening is:
- script runs
- script exits
- you're presented with the command prompt
- then the
echo Done $i
is sent to stdout and appears to overwrite the command prompt while leaving the cursor sitting on a new line (sans any command prompt)
In this scenario the script has exited and you're left sitting at the command prompt, but the delayed output from the background job makes it look like your program is still running.
Consider:
$ foo () { sleep 3; echo 'Done'; }
$ foo &
$ # immediately provided with command prompt
Three seconds later the terminal looks like:
$ foo &
$ Done # the 'Done' is added to the line and ...
# cursor is left sitting on blank line
At this point you're still at the command prompt ... it just doesn't look like it. From here you could run a command, eg:
$ foo &
$ Done
date
Fri Sep 24 12:28:05 CDT 2021
$
Or just hit <return>
to get a new command prompt, eg:
$ foo &
$ Done
# hit <return>
$
As other have pointed out, wait
will keep the script from exiting until all background jobs have completed.