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
Execute curl commands read from a file
提问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 curl
command 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")
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 $
.
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 echo
does is output its arguments to standard output (which means showing them on screen in your case).
所有echo
所做的就是输出它的参数标准输出(这意味着他们展示在屏幕上你的情况)。
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.
扩展一个变量($line
如上)实际上将它作为命令执行。因为文件中的行被正确引用,所以它应该可以工作。