Pass url to a bash script for use in scp

bash, scp, ssh

Solution

Your mistake is that you can `scp` to `user@server.com:` but not `ssh` to it : you need to remove the trailing `:` character (and possible path after it). You can do it easily like this with `bash` parameter expansion :

ssh "${URL%:*}" stat "$(basename "$F")"

RECOMMENDATIONS

- "USE MORE QUOTES!" They are vital. Also, learn the difference between ' and " and `. See http://mywiki.wooledge.org/Quotes and http://wiki.bash-hackers.org/syntax/words

- if you have spaces in filenames, your code will breaks things up. Better use `while IFS= read -r line; do #stuff with $line; done < file.txt`

- See bash parameter expansion

Problem

I'm writing a cron to backup some stuffs on a server. Basically I'm sending specific files form a local directory using scp. I'm using a public key to avoid authentication. For reusability I'm passing the local directory and the server url by arguments to my bash script. How I set my parameters: ``` #!/bin/bash DIR="$1" URL="$2" FILES="$DIR*.ext" ``` My problem is about formatting the url. Without formatting How I send files to the server: ``` #!/bin/bash for F in $FILEs do scp $F $URL; if ssh $URL stat $(basename "$F") then rm $F else echo "Fails to copy $F to $URL" fi done ``` If I try to copy at user's home on the server I do: ``` $ ~/backup /path/to/local/folder/ user@server.com: ``` If I try to copy at a specific directory on the server I do: ``` $ ~/backup /path/to/local/folder/ user@server.com:/path/to/remote/folder/ ``` In all cases it gives me the well known error (and my custom echo): ``` ssh: Could not resolve hostname user@server.com: nodename nor [...] Can't upload /path/to/local/folder/file.ext to user@server.com ``` And it works anyway (the file is copied). But that's not a solution, cause as scp fails (seems to), the file is never deleted. With formatting I tried sending files using this method: ``` #!/bin/bash for F in $FILES do scp $F "$URL:" done ``` I no longer get an error, and it works for copying at user's home directory then deleting the local file: ``` $ ~/backup /path/to/local/folder/ user@server.com ``` But, of course, sending to a specific directory don't work at all. Finally So I think that my first method is more appropriate, but how can I get rid of that error?

Original source