Baeldung Pro – Linux – NPI EA (cat = Baeldung on Linux)
announcement - icon

Learn through the super-clean Baeldung Pro experience:

>> Membership and Baeldung Pro.

No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.

Partner – Orkes – NPI EA (tag=Kubernetes)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

1. Overview

As Linux administrators, we sometimes need to check if certain files exist on the remote machine for system maintenance, troubleshooting, or configuration verification. Thankfully, SSH provides a powerful and secure way to execute commands remotely, including checking the existence of a file.

In this tutorial, we’ll discuss possible command-line approaches to verify the presence of a file on a remote Linux host via SSH:

  • test command for quick file checking
  • stat command for getting detailed file information
  • scp command for a secure and straightforward check
  • rsync command for efficient checks without transferring files

Further, we show the use of sshfs to mount the remote filesystem for direct access to files.

2. Executing Commands Remotely via SSH

Before diving into file existence checks, let’s quickly review how to execute commands remotely over SSH. SSH (Secure Shell) not only provides a secure way to connect to remote servers but also enables us to run commands on those servers directly from the local machine.

We can execute commands remotely over SSH by following a fairly simple syntax:

$ ssh user@remote_host <command>

In this syntax, we specify two parts:

  • user@remote_host with the respective user and host address or name
  • <command> with the desired command to run

This way, we can pick the command to use for the current scenario.

3. Using test Command

Generally, the test command is used to check file types and compare values. We leverage its -f option combined with SSH to quickly examine the presence of regular files (not directories or symlinks) on a remote host. Moreover, if the file is a symbolic link, we can use the -L option.

3.1. Syntax

So, let’s view the syntax of the test command for checking file existence:

$ ssh user@remote_host test -f /path/to/file && echo "File exist" || echo "File doesn't exist"

Thus, we see the respective message whether the file is available or not.

3.2. Practical Example

For instance, let’s say we want to check the file path /home/henry/SecurityKeys/keys.txt on the remote host [email protected]:

$ sudo ssh [email protected] test -f /home/henry/SecurityKeys/keys.txt && echo "File exists" || echo "File doesn't exist"
[email protected]'s password: 
File exists

In this case, we can see that the file /home/henry/SecurityKeys/keys.txt exists.

4. Using stat Command

Next, the stat command provides information about a file including its size, permissions, and timestamps. Thus, we can use stat with SSH to get the detailed file information if it exists. If the file doesn’t exist, we should see an error message.

4.1. Syntax

First, let’s take a look at the syntax of the stat command for file checking:

$ ssh user@remote_host stat /path/to/file

4.2. Practical Example

Now, let’s demonstrate with a practical example and check the file path /home/henry/Desktop/file.txt on the remote host [email protected] via stat:

$ ssh [email protected] stat /home/henry/Desktop/file.txt
[email protected]'s password: 
  File: /home/henry/Desktop/file.txt
  Size: 57        	Blocks: 8          IO Block: 4096   regular file
Device: 803h/2051d	Inode: 1216264     Links: 1
Access: (0664/-rw-rw-r--)  Uid: ( 1000/   henry)   Gid: ( 1000/   henry)
Access: 2024-10-16 16:39:50.266303879 +0500
Modify: 2024-10-16 16:52:30.419389524 +0500
Change: 2024-10-16 16:52:30.419389524 +0500
 Birth: 2024-10-16 16:39:50.266303879 +0500

As a result, we confirm that the file /home/henry/Desktop/file.txt exists. Further, we see detailed information including file size, permissions, and timestamps.

5. Using scp Command

To begin with, the scp command is mainly used to copy files between two hosts securely. However, we can attempt to copy a remote file without completing the transfer (passing the file to /dev/null) as a way of checking if the file exists.

This way, if the file is missing, the scp command returns an error. This approach is useful when we want a quick, secure, and straightforward way to perform existence checks.

5.1. Syntax

We can use the scp command for checking files by following a basic syntax:

$ scp user@remote_host:/path/to/file /dev/null

Critically, this method uses bandwidth for the check, because scp still reads the file even though it’s not really needed. For large files, this could be inefficient.

5.2. Practical Example

For example, let’s try checking the file path /home/henry/Documents/report.txt this time on the remote host [email protected]:

$ sudo scp [email protected]:/home/henry/Documents/report.txt /dev/null
[email protected]'s password: 
report.txt                                               100%   30     8.0KB/s   00:00

In this case, we copied the file report.txt to /dev/null to avoid saving it but can confirm that the file exists on the remote host.

6. Using rsync Command

Additionally, although the rsync command is known for synchronizing files between two hosts, we can also use it for verifying the file’s existence using the –dry-run option. This option simulates a file transfer without actually moving the files and is useful in cases when we require efficient, network-friendly, and large-scale file verification.

6.1. Syntax

First, let’s see the basic syntax to use when checking for files via rsync:

$ rsync --dry-run user@remote_host:/path/to/file 

6.2. Practical Example

For example, to check the file presence /home/henry/newfile.txt on the remote host [email protected], we can execute a fairly straightforward command:

$ sudo rsync --dry-run [email protected]:/home/henry/newfile.txt
[email protected]'s password: 
-rw-rw-r--             22 2024/10/18 16:16:14 newfile.txt

Consequently, the output confirms that the file /home/henry/newfile.txt exists on the remote host, displaying its name, size, permissions, and timestamp without transferring the file.

7. Using sshfs Command

The sshfs (secure shell file transfer) enables us to mount a remote filesystem over SSH. Additionally, we can mount the remote filesystem and directly access the files on the local machine. Afterward, we can use any standard Linux command to check for file existence.

7.1. Syntax

First, let’s see the general syntax for mounting a remote director using sshfs:

$ sshfs user@remote_host:/remote/directory /local/mountpoint

In the above syntax, we put the remote directory path to be mounted, and the local mounting point.

7.2. Practical Example

To illustrate, let’s try mounting the /home/henry directory from the remote host [email protected] to the local directory /mnt:

$ sudo sshfs [email protected]:/home/henry /mnt
[email protected]'s password:

Now, we can simply use the ls command to list the directory contents. For example, to list the /Documents directory, we can run this command:

$ sudo ls /mnt/Documents
report.txt

In return, we can see that the directory contains one file named report.txt.

Of course, any other local check should work as well with the respective path.

8. Conclusion

In this article, we’ve explored several approaches for checking the existence of a file on a remote host via SSH. These approaches include using the test, stat, scp, and rsync. In addition, we delved into SSHFS as a way to ease this process.

Initially, we saw how to run a command remotely via SSH. After that, we considered the syntax for each file existence check command and then demonstrated practical examples.