How to Check if a Directory Exists on a Remote Server Using Shell Script


2 views

When automating deployments or system administration tasks, you often need to verify directory existence on remote servers before performing operations. This prevents errors and allows for conditional logic in your scripts.

The most reliable approach uses SSH to execute commands remotely. Here are several methods:


# Method 1: Using test command
if ssh user@remote-server "[ -d '/path/to/directory' ]"; then
    echo "Directory exists"
else
    echo "Directory does not exist"
fi

# Method 2: Using ls with error redirection
ssh user@remote-server "ls /path/to/directory 2>/dev/null"
if [ $? -eq 0 ]; then
    echo "Directory exists"
else
    echo "Directory does not exist"
fi

Here's a practical deployment script that checks for and creates directories as needed:


#!/bin/bash

REMOTE_USER="deploy"
REMOTE_HOST="example.com"
TARGET_DIR="/var/www/myapp"

# Check directory existence
if ! ssh ${REMOTE_USER}@${REMOTE_HOST} "[ -d '${TARGET_DIR}' ]"; then
    echo "Creating directory ${TARGET_DIR}"
    ssh ${REMOTE_USER}@${REMOTE_HOST} "sudo mkdir -p ${TARGET_DIR} && sudo chown ${REMOTE_USER}:www-data ${TARGET_DIR}"
fi

# Proceed with deployment
rsync -avz --delete ./dist/ ${REMOTE_USER}@${REMOTE_HOST}:${TARGET_DIR}/

Robust scripts should handle various failure scenarios:

  • SSH connection failures
  • Permission issues
  • Disk space limitations
  • Network interruptions

# Enhanced version with error handling
check_remote_dir() {
    local dir="$1"
    if ! ssh -o ConnectTimeout=10 ${REMOTE_USER}@${REMOTE_HOST} "[ -d '${dir}' ]"; then
        if ! ssh ${REMOTE_USER}@${REMOTE_HOST} "sudo mkdir -p ${dir}"; then
            echo "Failed to create directory ${dir}" >&2
            return 1
        fi
    fi
    return 0
}

For more complex scenarios, consider these alternatives:


# Using Ansible
- name: Check if directory exists
  stat:
    path: "/path/to/directory"
  register: dir_stat

- name: Create directory if needed
  file:
    path: "/path/to/directory"
    state: directory
    mode: '0755'
  when: not dir_stat.stat.exists

# Using Python with Paramiko
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('remote-server', username='user')

stdin, stdout, stderr = ssh.exec_command('[ -d "/path/to/directory" ] && echo exists')
if 'exists' in stdout.read().decode():
    print("Directory exists")
else:
    print("Directory doesn't exist")

When automating application deployments, one of the first things we need to verify is whether target directories exist on remote servers. This becomes crucial when uploading build artifacts or configuration files via scripts.

The most reliable method is using SSH to execute remote commands. Here's a basic implementation:

if ssh user@remotehost "[ -d '/path/to/directory' ]"; then
    echo "Directory exists"
else
    echo "Creating directory..."
    ssh user@remotehost "mkdir -p /path/to/directory"
fi

We should account for various scenarios:

  • SSH connection failures
  • Permission issues
  • Symbolic links

Here's a more robust version with error handling:

remote_check() {
    if ssh -o ConnectTimeout=5 user@remotehost "[ -d '$1' ]" 2>/dev/null; then
        return 0
    else
        return 1
    fi
}

target_dir="/var/www/app"
if ! remote_check "$target_dir"; then
    echo "Directory missing, creating..."
    if ! ssh user@remotehost "mkdir -p '$target_dir' && chmod 755 '$target_dir'"; then
        echo "Creation failed!" >&2
        exit 1
    fi
fi

For environments where SSH isn't available or suitable:

Using SCP

if scp user@remotehost:"/path/to/directory/.testfile" /tmp 2>/dev/null; then
    echo "Directory exists"
else
    echo "Creating directory..."
    # SCP doesn't support directory creation, would need to chain SSH
fi

Using rsync

if rsync --list-only user@remotehost:/path/to/directory/ 2>/dev/null; then
    echo "Directory exists"
else
    echo "Creating directory with rsync"
    rsync -a --include='/' --exclude='*' /tmp/empty/ user@remotehost:/path/to/directory/
fi

When running these checks in loops or frequent deployments:

  • Use SSH connection multiplexing
  • Consider caching results if appropriate
  • Combine multiple operations into single SSH connections
# Using SSH ControlMaster for multiple operations
if ssh -o ControlMaster=auto -S /tmp/ssh_mux_%h_%p_%r user@remotehost \
    "[ -d '/path/to/dir' ] || { mkdir -p '/path/to/dir' && chmod 755 '/path/to/dir'; }"; then
    echo "Directory ready"
fi