简体   繁体   English

将变量放入 bash for 循环

[英]Put variable in bash for loop

I am making a post request in bash multiple times with a for loop like:我在 bash 中多次使用 for 循环发出发布请求,例如:

     for n in {1..5}; do curl -X POST   'http://localhost:8080/hello'   -H 'accept: */*'   -H 'Content-Type: application/json'   -d '{
    "a": 1,
    "b": 2
      }';done

Now the values a and b are the same so I wanted to generate random values for the variables.So I created two random values:现在 a 和 b 的值相同,所以我想为变量生成随机值。所以我创建了两个随机值:

a= awk -v min=10 -v max=20 -v num=1 'BEGIN{srand(); for (i=1;i<=num;i++) printf ("%.5f\n",min+rand()*(max-min+1))}'
b= awk -v min=50 -v max=60 -v num=1 'BEGIN{srand(); for (i=1;i<=num;i++) printf ("%.5f\n",min+rand()*(max-min+1))}'

and tried to insert them into my post request like this:并尝试将它们插入到我的帖子请求中,如下所示:

     for n in {1..5}; do curl -X POST   'http://localhost:8080/hello'   -H 'accept: */*'   -H 'Content-Type: application/json'   -d '{
  "a": a,
  "b": b
}';done

but it didnt work I also tried:但它没有用我也试过:

 for (n in {1..5};a=    awk -v min=10 -v max=20 -v num=1 'BEGIN{srand(); for (i=1;i<=num;i++) printf ("%.5f\n",min+rand()*(max-min+1))}'; b=    awk -v min=50 -v max=60 -v num=1 'BEGIN{srand(); for (i=1;i<=num;i++) printf ("%.5f\n",min+rand()*(max-min+1))}'); do curl -X POST   'http://localhost:8080/hello'   -H 'accept: */*'   -H 'Content-Type: application/json'   -d '{
  "a": 1,
  "b": 2
}';done

but that also didnt work, what am I doing wrong?但这也没有用,我做错了什么?

Thanks in regard致谢

You must perform some small corrections so you can use all of this in a script.您必须执行一些小的更正,以便您可以在脚本中使用所有这些。

Next you can see the values being replaced (a and b).接下来您可以看到被替换的值(a 和 b)。 Adapt for what you need适应你的需要

a=`awk -v min=10 -v max=20 -v num=1 'BEGIN{srand(); for (i=1;i<=num;i++) printf ("%.5f\n",min+rand()*(max-min+1))}'`
b=`awk -v min=50 -v max=60 -v num=1 'BEGIN{srand(); for (i=1;i<=num;i++) printf ("%.5f\n",min+rand()*(max-min+1))}'`


for n in {1..5}; do 
  echo curl -X POST   'http://localhost:8080/hello'   -H 'accept: */*'   -H 'Content-Type: application/json'   -d "{

  \"a\": $a,

  \"b\": $b

}";done

The first problem is that you want a and b to have the result of awk command.第一个问题是您希望 a 和 b 具有 awk 命令的结果。 For that you need to (for example) enclose the command between ``为此,您需要(例如)将命令括在``之间

To have the variables being substituted you cannot have them between '...' (single quotes).要替换变量,您不能将它们放在“...”(单引号)之间。 Otherwise they are not substituted.否则它们不会被替换。 So you must use double quotes "..." to have $a and $b being substituted by their variable values.所以你必须使用双引号 "..." 来让 $a 和 $b 被它们的变量值代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM