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?
Your mistake is that you can
scptouser@server.com:but notsshto it : you need to remove the trailing:character (and possible path after it). You can do it easily like this withbashparameter expansion :RECOMMENDATIONS
while IFS= read -r line; do #stuff with $line; done < file.txt