在Bash脚本中使用循环变量来传递不同的命令行参数 [英] Using a loop variable in a Bash script to pass different command-line arguments

查看:97
本文介绍了在Bash脚本中使用循环变量来传递不同的命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++程序,我使用命令行输入了两个双精度值作为输入,

I have a C++ program to which I pass two doubles as inputs from the command line using

int main(int argc, char *argv[]){
    double a,b;
    a = atof(argv[1]);
    b = atof(argv[2]);
    further code.....

我使用qsub实用程序在群集上运行代码,并且我有一个名为'jobsub.sh'的Bash脚本来提交作业,如下所示:

I run the code on a cluster using the qsub utility and I have a Bash script named 'jobsub.sh` to submit the jobs which looks like this:

#!/bin/csh -f
hostname
cd /home/roy/codes/3D             # Change directory first -- replace Mysubdir
set startdir = `pwd`               # Remember the directory we're in
if( ! -d /scratch/$USER ) then
    mkdir /scratch/$USER       # Create scratch directory
endif                              # If it does not exist
#cp infile12 /scratch/$USER     # Copy input file to scratch directory
cd /scratch/$USER                  # Change to scratch directory
#rm *.*
$HOME/codes/3D/autoA100.out 2.1 2.2          # Run a program
cp * $startdir         # Copy outputfiles back to where we started

在终端机上,执行qsub jobsub.sh.

但是,我想在不同的内核上为ab的不同值并行运行相同的可执行文件.是否可以在Bash脚本中编写for循环,以便我可以做类似的事情,

However, I want to run the same executable for different values of a and b in parallel on different cores. Is it possible to write a for loop in the Bash script so that I can do something like,

for i=1;i<=10;i++ {
   $HOME/codes/3D/autoA100.out 2+i*0.1 2+i*0.2
}

推荐答案

如果要将执行脚本提交给批处理加载器,则无法通过简单的循环来执行所需的执行,因为整个脚本每个节点上运行.但是,大多数批处理加载器会向用户提供环境变量.

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具有$PBS_ARRAYID,它指定作业正在运行时的唯一ID.因此,除了使用循环之外,您的脚本还可以具有:

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

注意,我已经在上面的$PBS_ARRAYID中添加了1,因为ID从0开始,而循环从1开始.还值得一提的是,尽管bash可以本地执行一些算术运算,但它无法处理实数;这就是为什么我必须调用bc.

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.

这篇关于在Bash脚本中使用循环变量来传递不同的命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆