How to test if remote dir exist?

Hello, :slight_smile:

I'm trying to test if a remote directory exist per ssh, I have already made a ssh key and it works :

#!/bin/bash

HOST="10.10.1.22"
FILE_PATH="/var/wwww/html"

ssh -q $HOST [[ -d $FILE_PATH ]] && echo "Directory exists" || echo "Directory does not exist";

Output :

rsync-user@vmtest1:/home/scripts$ ./test.sh
Directory does not exist

That the directory exist or not, that's always the same output :frowning:
Thanks by advance :b:

The && and || are evaluated locally.
Enclose them in quotes

ssh -qnx $HOST "test -d $FILE_PATH && echo 'Directory exists' || echo 'Directory does not exist'"

I have chosen the "quotes" because $FILE_PATH should be substituted, and therefore the 'ticks' for the echo.

1 Like

Thanks ! It works also, I just found my mistake..

FILE_PATH="/var/wwww/html"

You will find, that ssh , when executed as a securified rexec -replacement, returns the error code of the remotely executed program.

You could, therefore, equally try the likes of:

if ! ssh "${user}@${host}" "ls /dir/in/question >/dev/null 2>&1" ; then
     echo "dir does not exist"
else
     echo "dir does exist"
fi

Which would not be of much use in your context (it would i.e. produce false positives if "/dir/in/question" would be a file) but you can use this mechanism to generally execute commands remotely while testing for their return code - UNIX convention is to return 0 on success and something else for the various reasons of being unsuccessful.

I hope this helps.

bakunin

1 Like

I had no think, why not, it's an easy way, thanks for your reply :b: