Using filename with spaces with scp and chmod in bash

From time to time, I like to put files in the / tmp directory of my web server for distribution. What is annoying is that I have to set permissions whenever I view files. Following the advice of another question , I wrote a script file that copies the file, sets 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 run the script with an argument including spaces. Although I suspect that the solution might be to use $ @ , I still haven't figured out how to get the pending file name to work with.

+3
source share
3 answers

It turns out that you must avoid the path that will be sent to the remote server. Bash counts the quotes in SERVER: "/ var / www / tmp / $ 1" is associated with $ 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

The echo we see is trying to execute:

scp SERVER:/var/www/tmp/Screen shot 2010-02-18 at 9.38.35 AM.png

If the quotes are escaped literals instead, the scp command is more like expected:

scp SERVER:"/var/www/tmp/Screen shot 2010-02-18 at 9.38.35 AM.png"

With the addition of some code to trim 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"
+4
source

The script looks right. I assume that you need to specify the file name when you pass it to your script:

scp-chmod.sh "filename with spaces"

Or remove the spaces:

scp-chmod.sh filename\ with\ spaces
0
source

, ( ), - , . , . " ", .

-5

Source: https://habr.com/ru/post/1735876/