How do I create a directory on remote host if it doesn't exist without ssh-ing in?

larjudge picture larjudge · Aug 27, 2009 · Viewed 73.7k times · Source

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. Argument 1 is the file and argument 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 have got no choice, then I have got no choice.

Answer

Peter Mortensen picture Peter Mortensen · Aug 27, 2009

You can use rsync.

For example,

rsync -ave ssh fileToCopy ssh.myhost.net:/some/nonExisting/dirToCopyTO

Note about rsync:

rsync is utility software and network protocol for Unix which synchronizes files and directories from one location to another. It minimizes data transfer sizes by using delta encoding when appropriate using the rsync algorithm which is faster than other tools.