开发者

Using a filename with spaces with scp and chmod in bash

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'v开发者_运维知识库e 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.


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:

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 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="$1"

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"


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜