在 bash 中通过 scp 和 chmod 使用带空格的文件名
我喜欢定期将文件放在网络服务器的 /tmp 目录中以进行共享。令人烦恼的是,每当我 scp 文件时,我都必须设置权限。按照另一个问题的建议,我编写了一个复制文件的脚本结束,设置权限,然后打印 URL:
#!/bin/bash
scp "$1" SERVER:"/var/www/tmp/$1"
ssh SERVER chmod 644 "/var/www/tmp/$1"
echo "URL is: http://SERVER/tmp/$1"
当我用实际主机替换 SERVER 时,一切都会按预期工作......直到我使用包含空格的参数执行脚本。虽然我怀疑解决方案可能是使用 $@ 我还没有弄清楚如何让空格文件名起作用。
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 question I've written a script which copies the file over, sets the permissions and then prints the URL:
#!/bin/bash
scp "$1" SERVER:"/var/www/tmp/$1"
ssh SERVER chmod 644 "/var/www/tmp/$1"
echo "URL is: http://SERVER/tmp/$1"
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
事实证明,我们需要的是转义将发送到远程服务器的路径。 Bash 认为 SERVER:"/var/www/tmp/$1" 中的引号与 $1 相关,并将它们从最终输出中删除。如果我尝试运行:
Echoing 我们看到它正在尝试执行:
如果引号是转义文字,则 scp 命令看起来更像您所期望的:
通过添加一些代码来截断路径,最终脚本将变为:
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:
Echoing we see it is trying to execute:
If instead the quotes are escaped literals then the scp command looks more like you'd expect:
With the addition of some code to truncate the path the final script becomes:
剧本看起来不错。我的猜测是,当您将文件名传递到脚本中时,您需要引用文件名:
或者转义空格:
The script looks right. My guess is that you need to quote the filename when you pass it into your script:
Or escape the spaces:
不用担心文件名中的空格(除了引用之外)的更简单方法是在传输之前重命名文件以消除空格。或者,当您创建文件时,不要使用空格。每当您命名文件时,您都可以将此作为您的“最佳实践”。
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.