foobar666
foobar666

Reputation: 11

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.

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": "[email protected]"}]';
/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": "[email protected]"}]';

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.

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

Upvotes: 0

Views: 343

Answers (2)

Paul Hodges
Paul Hodges

Reputation: 15246

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. grep -vf errs x to get the ones that succeeded. (Will include the trap.)

Upvotes: 0

l0b0
l0b0

Reputation: 58768

To run each command listed in a file called commands.txt, simply treat it as a script: bash commands.txt.

That said, the loop has several issues:

  1. Overriding IFS globally is going to cause some weird behaviour. Basically you'll only ever want to override it for a single command, as in IFS=$'\n' COMMAND.
  2. Use $(COMMAND) instead of backticks.
  3. Don't loop over lines using for.
  4. You'll want to put a command into an array to handle non-trivial arguments (such as those containing whitespace).

Upvotes: 1

Related Questions