Using a loop variable in a Bash script to pass different command-line arguments

五迷三道 提交于 2019-11-29 16:31:40

If you are submitting the execution script to a batch loader, then there is no way to have a simple loop do the execution like you want because the entire script is run on each node. However, most batch loaders provide environment variables to the user.

PBS, for example, has $PBS_ARRAYID, which specifies the unique ID for the job as it is running. So instead of using a loop, your script can have:

a=$(echo "2+($PBS_ARRAYID+1)*0.1" | bc -l)
b=$(echo "2+($PBS_ARRAYID+1)*0.2" | bc -l)
$HOME/codes/3D/autoA100.out $a $b

Notice I've added 1 to $PBS_ARRAYID above because the ID begins from 0 while your loop begins from 1. It's also worth mentioning that while bash can do some arithmetic natively, it cannot handle real numbers; that's why I had to invoke bc.

You can always run jobs in the background (in which case the shell will continue with the next instruction)

MY_PIDS=
for i in 1 2 3 4 5 6 7 8 9 10
do
    yourjob "$(a i)" "$(b i)" &   # Note the ampersand (background)
    MY_PIDS="$MY_PIDS "$!         # Do not write the $! inside the quotes, bash will
                                  # break (better, don't use bash but plain sh)
done

# Wait wor each job to complete and cleanup
for p in $MY_PIDS
do
    wait "$p"
    echo "Return code of job $p is $?"
    do_cleanup_for "$p"
done

But certainly you need to make sure that the jobs running in parallel are not stepping on each other's feet (like writing to the same file).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!