在 bash 中使用带空格的文件名和 scp 和 chmod
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2399724/
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
Using a filename with spaces with scp and chmod in bash
提问by speciousfool
Periodically, I like to put files in the /tmp directory of my webserver to share out. What is annoying is that I must set the permissions whenever I scp the files. Following the advice from another questionI've written a script which copies the file over, sets the permissions and then prints the URL:
每隔一段时间,我喜欢将文件放在我的网络服务器的 /tmp 目录中以进行共享。令人讨厌的是,每当我 scp 文件时,我都必须设置权限。按照另一个问题的建议,我编写了一个脚本来复制文件,设置权限,然后打印 URL:
#!/bin/bash
scp "" SERVER:"/var/www/tmp/"
ssh SERVER chmod 644 "/var/www/tmp/"
echo "URL is: http://SERVER/tmp/"
When I replace SERVER with my actual host, everything works as expected...until I execute the script with an argument including spaces. Although I suspect the solution might be to use $@ I've not yet figured out how to get a spaced filename to work.
当我用我的实际主机替换 SERVER 时,一切都按预期工作......直到我使用包含空格的参数执行脚本。虽然我怀疑解决方案可能是使用 $@ 我还没有想出如何让一个空格的文件名工作。
回答by speciousfool
It turns out that what is needed is to escape the path which will be sent to the remote server. Bash thinks the quotes in SERVER:"/var/www/tmp/$1" are related to the $1 and removes them from the final output. If I try to run:
事实证明,需要的是转义将发送到远程服务器的路径。Bash 认为 SERVER:"/var/www/tmp/$1" 中的引号与 $1 相关,并将它们从最终输出中删除。如果我尝试运行:
tmp-scp.sh Screen\ shot\ 2010-02-18\ at\ 9.38.35\ AM.png
Echoing we see it is trying to execute:
回显我们看到它正在尝试执行:
scp SERVER:/var/www/tmp/Screen shot 2010-02-18 at 9.38.35 AM.png
If instead the quotes are escaped literals then the scp command looks more like you'd expect:
如果引号是转义的文字,那么 scp 命令看起来更像您期望的:
scp SERVER:"/var/www/tmp/Screen shot 2010-02-18 at 9.38.35 AM.png"
With the addition of some code to truncate the path the final script becomes:
添加一些代码来截断路径,最终脚本变为:
#!/bin/bash
# strip path
filename=${1##*/}
fullpath=""
scp "$fullpath" SERVER:\"/var/www/tmp/"$filename"\"
echo SERVER:\"/var/www/tmp/"$filename"\"
ssh SERVER chmod 644 \"/var/www/tmp/"$filename"\"
echo "URL is: http://SERVER/tmp/$filename"
回答by leedm777
The script looks right. My guess is that you need to quote the filename when you pass it into your script:
剧本看起来不错。我的猜测是您需要在将文件名传递到脚本时引用它:
scp-chmod.sh "filename with spaces"
Or escape the spaces:
或转义空格:
scp-chmod.sh filename\ with\ spaces
回答by ghostdog74
the easier way without worrying about spaces in file names, (besides quoting) is to rename your files to get rid of spaces before transferring. Or when you create the files, don't use spaces. You can make this your "best practice" whenever you name your files.
无需担心文件名中的空格的更简单方法(除了引用)是重命名文件以在传输之前去除空格。或者在创建文件时,不要使用空格。每当您命名文件时,您都可以将此作为“最佳实践”。

