How to check if a file exists on a remote server

There are circumstances where you want to test if a file exists somewhere on a remote Linux server (e.g., /var/run/test_daemon.pid), without logging in to the server interactively. For example, you may want your script to behave differently depending on whether or not a specific file exists on a remote server.

In this tutorial, I will show you how to check if a remote file exists in different script languages (e.g., Bash shell, Perl, Python).

The approach described here will use ssh to access a remote host. You first need to enable password-less ssh login to the remote host, so that your script can access a remote host in non-interactive batch mode. You also need to make sure that ssh login has read permission on the file to check. Assuming that you have finished these two steps, you can write scripts like the following examples.

Check if a file exists on a remote server in Bash

#!/bin/bash

ssh_host="xmodulo@remote_server"
file="/var/run/test.pid"

if ssh $ssh_host test -e $file;
    then echo $file exists
    else echo $file does not exist
fi

Check if a file exists on a remote server in Perl

#!/usr/bin/perl

my $ssh_host = "xmodulo@remote_server";
my $file = "/var/run/test.pid";

system "ssh", $ssh_host, "test", "-e", $file;
my $rc = $? >> 8;
if ($rc) {
    print "$file doesn't exist\n";
} else {
    print "$file exists\n";
}

Check if a file exists on a remote server in Python

#!/usr/bin/python

import subprocess
import pipes

ssh_host = 'xmodulo@remote_server'
file = '/var/run/test.pid'

resp = subprocess.call(
    ['ssh', ssh_host, 'test -e ' + pipes.quote(file)])

if resp == 0:
    print ('%s exists' % file)
else:
    print ('%s does not exist' % file)

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of Xmodulo.com. He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.
Your name can also be listed here. Write for us as a freelancer.

One thought on “How to check if a file exists on a remote server

  1. Thank you for hitting a few different scripting languages when solving this question!!! I personally found it very helpful. Just an FYI, I always used '[-f "path-to-file]' and found that this works as well but I like your method better even though I get the same results. Thanks again friend!!!!!

Leave a comment

Your email address will not be published. Required fields are marked *

Current ye@r *