bash 执行从文件中读取的 curl 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41688381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:37:48  来源:igfitidea点击:

Execute curl commands read from a file

linuxbashshellcurl

提问by Ojen G.

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?

我有一个文本文件,其中包含 curl 调用。它们都由换行符分隔,这有助于我相应地逐行读取文件。我的问题是我不确定如何触发 curl 调用来执行。现在它的行为是像打印另一串字符一样打印到屏幕上?

Example of data.txt :

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.

它只会给出行的输出,而不是实际进行 curl 调用。

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"

回答by codeforester

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

您没有执行curl从输入文件读取的行中包含的命令。你可以通过改变这一行来做到这一点:

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

to

makingCurlCall=$(eval "$line")

or

或者

makingCurlCall=$("$line")

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

eval如果字符串中包含的命令具有任何需要由 shell 解释的元字符,则更合适。例如><、 和$

回答by Fred

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 echodoes is output its arguments to standard output (which means showing them on screen in your case).

所有echo所做的就是输出它的参数标准输出(这意味着他们展示在屏幕上你的情况)。

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

扩展一个变量($line如上)实际上将它作为命令执行。因为文件中的行被正确引用,所以它应该可以工作。