Check to see if a directory exists remotely (shell script)

33,872

Solution 1

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

if [[ `ssh [email protected] test -d /path/to/my/directory && echo exists` ]] ; then
    # put code in here
fi

Solution 2

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

Solution 3

Just use

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

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

Solution 4

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.

Share:
33,872

Related videos on Youtube

Admin
Author by

Admin

Updated on September 17, 2022

Comments

  • Admin
    Admin almost 2 years

    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!

  • ILIV
    ILIV over 14 years
    It can be accessed through SSH, however I wasn't sure if there is another tool that will allow me to create the directory.
  • Chopper3
    Chopper3 over 14 years
    If you have SSH simply script an mkdir, if it exists it'll just fail with an error.
  • ILIV
    ILIV over 14 years
    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.
  • Zoredache
    Zoredache over 14 years
    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.
  • Ashish Ashu
    Ashish Ashu over 14 years
    I added it, but it depends on what exactly he wants. Now he can't use the command in an if statement anymore.
  • chiborg
    chiborg about 14 years
    This didn't work for me (probably your backquotes got mangled). I used if [[ `ssh [email protected] test -d /path/to/my/directory && echo exists` ]] and that worked.