使用 Curl 下载文件的 Bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1444705/
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-09 18:32:23  来源:igfitidea点击:

Bash script for downloading files with Curl

bashcurldownloadsed

提问by Rob Cowell

I'm trying to knock together a little batch script for downloading files, that takes a URL as its first parameter and a local filename as its second parameter. In testing I've learned that its tripping up on spaces in the output filename, so I've tried using sed to escape them, but its not working.

我正在尝试组合一个用于下载文件的小批处理脚本,它将 URL 作为其第一个参数,将本地文件名作为其第二个参数。在测试中,我了解到它在输出文件名中被空格绊倒,所以我尝试使用 sed 来转义它们,但它不起作用。

#!/bin/bash
clear
echo Downloading 
echo
filename=`sed -e "s/ /\\ /g" `
echo $filename
echo eval curl -# -C - -o $filename 

but I get the message

但我收到了消息

sed: outfile.txt: No such file or directory

sed: outfile.txt: 没有那个文件或目录

which suggests its trying to load the output file as input to sed instead of treating the output filename as a string literal.

这表明它尝试将输出文件作为输入加载到 sed 而不是将输出文件名视为字符串文字。

What would be the correct syntax here?

这里的正确语法是什么?

回答by cms

quoting the arguments correctly, rather than transforming them might be a better approach

正确引用参数,而不是转换它们可能是更好的方法

It's quite normal to expect to have to quote spaces in arguments to shell scripts

期望必须在 shell 脚本的参数中引用空格是很正常的

e.g.

例如

#!/bin/bash
clear
echo Downloading 
echo `curl -# -C - -o "" ""`

called like so

像这样叫

./myscript http://www.foo.com "my file"

./myscript http://www.foo.com "my file"

alternatively, escape the spaces with a '\' as you call them

或者,在你调用它们时用 '\' 转义空格

./myscript http://www.example.com my\ other\ filename\ with\ spaces

回答by Nick Fortescue

I agree with cms. Quoting the input arguments correctly is much better style - what will you do with the next problem character? The following is much better.

我同意cms。正确引用输入参数是更好的风格 - 您将如何处理下一个问题字符?以下要好得多。

curl -# -C - -o "" 

However, I hate people not answering the asked question, so here's an answer :-)

但是,我讨厌人们不回答所提出的问题,所以这是一个答案:-)

#!/bin/bash
clear
echo Downloading 
echo
filename=`echo  | sed -e "s/ /\\ /g"`
echo $filename
echo eval curl -# -C - -o $filename 

回答by Paused until further notice.

curl -# -C - -o "" 

回答by sud03r

if $2is a text input then try

如果$2是文本输入然后尝试

echo  | sed 's: :\\ :g '

I generally avoid backslashes in sed delimiters are they are quite confusing.

我通常避免在 sed 分隔符中使用反斜杠,因为它们很容易混淆。