Ojen G.
Ojen G.

Reputation: 173

Execute curl commands read from a file

I have a text file which contains curl calls inside. They are all separated by new-line breaks which helps me when it comes to reading the file line by line accordingly. My problem is that I am not sure how to trigger the curl calls to execute. Right now its behavior is to print to screen like it was just another string of chars?

Example of data.txt :

curl -X GET "https://www.google.com"
curl -X GET "https://www.facebook.com"

My script :

#!/bin/sh
IFS=$'\n'
while read -r line
do
    echo $line
    makingCurlCall=$(echo "$line")
    echo "$makingCurlCall"
done < "data.txt"

It will only give the output of the lines and not actually making the curl calls.

Output:

curl -X GET "https://www.google.com"
curl -X GET "https://www.google.com"
curl -X GET "https://www.facebook.com"
curl -X GET "https://www.facebook.com"

Upvotes: 6

Views: 22563

Answers (2)

codeforester
codeforester

Reputation: 42979

You are not executing the curl command contained in the line read from the input file. You could do that by changing this line:

makingCurlCall=$(echo "$line") => this simply displays the command and not execute it

to

makingCurlCall=$(eval "$line")

or

makingCurlCall=$("$line")

eval is more appropriate if the command contained in the string has any meta characters that need to be interpreted by the shell. For example, >, <, and $.

Upvotes: 6

Fred
Fred

Reputation: 6995

Try replacing your script with this slightly modified version

#!/bin/sh
IFS=$'\n'
while read -r line
do
    echo $line
    $line
done < "data.txt"

All echo does is output its arguments to standard output (which means showing them on screen in your case).

Expanding a variable (like $line above) will actually execute it as a command. Because the lines in your file are properly quoted, it should work.

Upvotes: 2

Related Questions