views:

1894

answers:

3

I'm not sure if this is possible or not,

Basically, I'm writing a script that allows me to scp a file to my hosting. This is it so far. Arg 1 is the file and arg 2 is the folder i want it to be placed in on the remote server

function upload {
scp $1 [email protected]:$2
}

As you may/may not know, if the directory I specify when I call the function doesn't exist, then the transfer fails. Is there a way to check if the directory exists in the function and if it doesn't, create it.

I would prefer not having to ssh in every time and create the directory, but if I gots no choice, then I gots no choice.

Cheers, Lar

+1  A: 

If you do a recursive scp (-r), it will copy directories as well. So if you create a directory of the name you desire on the remote host locally, copy the file into it, and then recursively copy, the directory will be created, with the file in it.

Kind of awkward, but it would do the job.

Matthias Wandel
What if the remote directory already exists (and is not empty)?
mouviciel
+4  A: 

You can use rsync.

E.g.:

rsync -ave ssh fileToCopy ssh.myhost.net:/some/nonExisting/dirToCopyTO
Peter Mortensen
+1  A: 

I assume you mean you don't want to interactively log in and create directories by hand, rather than that you want to avoid using ssh altogether, since you still need a password or public key with scp.

If using ssh non-interactively is acceptable, then you can stream your file using cat over ssh:

cat $1 | ssh $2 "mkdir $3;cat >> $3/$1"

where

$1 = filename 
$2 = user@server
$3 = dir_on_server

If the directory already exists, mkdir complains but the file is still copied over. The existing directory will not be overwritten. If the directory does not exist, mkdir will create it.

ire_and_curses