简体   繁体   English

从bash中的文件读取时循环运行curl命令

[英]Running curl commads in a loop while reading from a file in bash

I'm trying to parse a file by line and then trying to run all the curl commands in it, and then logging the successful v/ unsuccessful calls.我正在尝试逐行解析文件,然后尝试运行其中的所有 curl 命令,然后记录成功的 v/ 不成功调用。

cat file 

/usr/bin/curl  -X POST http://localhost/services/migration -H 'Content-Type: application/json' -H 'cache-control: no-cache' -d ' [{"resources": [{"name": "Provisioned Throughput (at peek load)","value": "514"}],"entityTypes": [{"app": "thanos"}],"subEntityTypes": [{"vapps": "loki-odinson"}],"user": "foobar@tt.com"}]';
/usr/bin/curl  -X POST http://localhost/services/migration -H 'Content-Type: application/json' -H 'cache-control: no-cache' -d ' [{"resources": [{"name": "Provisioned Throughput (at peek load)","value": "5124"}],"entityTypes": [{"app": "stark"}],"subEntityTypes": [{"vapps": "tony-s"}],"user": "foobar@tt.com"}]';

I am parsing the file by line.我正在逐行解析文件。 echo statement works fine and gives me curl command, but when I try to run it plainly, it gives me -bash: No such file or directory error. echo 语句工作正常并给我 curl 命令,但是当我尝试简单地运行它时,它给了我 -bash: No such file or directory 错误。

I could source the whole file but that would be a pain in logging to see how many failed vs succeeded.我可以获取整个文件,但是在记录中查看失败与成功的次数会很痛苦。

Below is the command im trying to run.下面是我试图运行的命令。

IFS=$'\n'
for var in `cat ten`; do $var ; sleep 1 ; done

To run each command listed in a file called commands.txt, simply treat it as a script: bash commands.txt .要运行名为 commands.txt 的文件中列出的每个命令,只需将其视为脚本: bash commands.txt

That said, the loop has several issues:也就是说,循环有几个问题:

  1. Overriding IFS globally is going to cause some weird behaviour.全局覆盖IFS会导致一些奇怪的行为。 Basically you'll only ever want to override it for a single command, as in IFS=$'\\n' COMMAND .基本上,您只想为单个命令覆盖它,如IFS=$'\\n' COMMAND
  2. Use $(COMMAND) instead of backticks .使用$(COMMAND)而不是反引号
  3. Don't loop over lines using for .不要使用for遍历行
  4. You'll want to put a command into an array to handle non-trivial arguments (such as those containing whitespace).您需要将命令放入数组中以处理重要参数(例如包含空格的参数)。

Try setting a trap.尝试设置陷阱。

$:  cat x
trap 'echo "$BASH_COMMAND">>errs' ERR
echo 1 2 3 4
bogus 5 6 7 8
true this one
false this one
$: ./x
1 2 3 4
bash: bogus: command not found
$: cat errs
bogus 5 6 7 8
false this one
./x

errs is now the list of the ones that failed. errs现在是失败的列表。 grep -vf errs x to get the ones that succeeded. grep -vf errs x获取成功的那些。 (Will include the trap.) (将包括陷阱。)

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

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