9

Is there a way to see if a directory exists on a remote server?

Perhaps there's a better way, but I'm writing an application deployment script, and I want to create a directory on a remote server if the directory doesn't exist to place the files.

Thanks in advance!

7 Answers7

6

You can use ssh to call a programme on the remote host, test tests for certain conditions.

if [[ `ssh user@example.com test -d /path/to/my/directory && echo exists` ]] ; then
    # put code in here
fi
the-wabbit
  • 40,737
  • 13
  • 111
  • 174
Amandasaurus
  • 31,471
  • 65
  • 192
  • 253
  • 2
    This didn't work for me (probably your backquotes got mangled). I used `if [[ \`ssh user@example.com test -d /path/to/my/directory && echo exists\` ]]` and that worked. – chiborg May 28 '10 at 08:31
4
mkdir -p

But if that isn't quite what you're after you can check the existence of a directory with

ssh user@host test -d /home && echo exists
ptman
  • 28,394
  • 2
  • 30
  • 45
3

Just use

ssh remoteHost 'mkdir -p /whatever/your/dir/is'

It will create the dir if it doesn't already exist.

Kim
  • 769
  • 1
  • 5
  • 12
  • 1
    if you add a `-p` to your mkdir command it will not report an error if the directory already exists and it will make the entire path. – Zoredache Jan 15 '10 at 21:02
  • I added it, but it depends on what exactly he wants. Now he can't use the command in an if statement anymore. – Kim Jan 16 '10 at 07:08
1

I'd recommend looking at using the RPM mechanism to install your application, rather than writing something home grown, since the problems you'll come across with your own script will almost certainly have already been solved with RPM. Here's an excellent tutorial on RPM.

gareth_bowles
  • 9,127
  • 9
  • 34
  • 42
0

How do you intend to talk to this remote server? SSH, SMB, NFS, something else? there's usually a way of finding this stuff out but you'll need to know what protocols and authentication option you have open to you before knowing exactly how to to this.

Chopper3
  • 101,299
  • 9
  • 108
  • 239
  • It can be accessed through SSH, however I wasn't sure if there is another tool that will allow me to create the directory. –  Jan 15 '10 at 19:49
  • If you have SSH simply script an mkdir, if it exists it'll just fail with an error. – Chopper3 Jan 15 '10 at 20:01
  • Yeah, after doing some research, this is the way I'll be doing it. I'm kind of a linux noob, so I didn't realize you could execute a script and have it continue to execute commands remotely. –  Jan 15 '10 at 20:03
0
#its simple

if [[ "`ssh -q hostname ls /dir/filename.abc 2>dev/null`" == "/dir/filename.abc" ]]
then
echo "file exists"
else
echo "file not exists"
fi 
Andrew Schulman
  • 8,811
  • 21
  • 32
  • 47
0
if ssh $REMOTE_HOST ls $BACKUP_DIR_REMOTE/$REMOTE_DAILY;
then
    ssh $REMOTE_HOST btrfs subvolume delete $BACKUP_DIR_REMOTE/$REMOTE_DAILY
else
    echo "Older snapshot does not exist."
fi
mforsetti
  • 2,666
  • 2
  • 16
  • 20