Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 419
larjudge Avatar asked Aug 27 '09 09:08

larjudge


People also ask

Can you SCP a directory in Linux?

To copy a directory (and all the files it contains), use scp with the -r option. This tells scp to recursively copy the source directory and its contents. You'll be prompted for your password on the source system ( deathstar.com ).

Does rsync create directory?

Rsync creates a directory with the same name inside of destination directory - Server Fault. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.


2 Answers

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.

like image 161
Peter Mortensen Avatar answered Oct 04 '22 12:10

Peter Mortensen


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.

like image 37
ire_and_curses Avatar answered Oct 04 '22 11:10

ire_and_curses