9

This question has been already posted but I would like to know if there is a way to know if a directory exists on a remote machine with ssh BUT from the command line directly and not from a script. As I saw in this previous post: How to check if dir exists over ssh and return results to host machine, I tried to write in the command line the following:

ssh armand@127.0.0.1 '[ -d Documents ]'

But this does not print anything. I would like to know if there's a way to display an answer easily.

codeforester
  • 39,467
  • 16
  • 112
  • 140
hackchoc
  • 115
  • 1
  • 1
  • 5

2 Answers2

8

This is a one liner:

ssh armand@127.0.0.1 '[ -d Documents ] && echo exists || echo does not exist'
Jahid
  • 21,542
  • 10
  • 90
  • 108
4

That command will just return whether or not the Documents directory exists, you can extend the answer in the linked question to do something if it does like:

if ssh armand@127.0.0.1 '[ -d Documents ]'; then
    printf "There is a Documents directory\n"
else
    printf "It does not exist, or I failed to check at all\n"
fi

or if you want to store whether or not it exists in a variable you could do something like

ssh armand@127.0.0.1 '[ -d Documents ]'
is_a_directory=$?

now if is_a_directory contains 0 you know there is a Documents directory, otherwise there is not such a directory or we failed to ssh and find out

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
  • 3
    Techinically, this will print "It does not exist" even if the directory exists but the connection attempt fails for some reason. – chepner Nov 30 '15 at 21:41
  • But there is no way to catch from this command a variable such a boolean to know if this exists ? I actually want to run this command from a python script and this would be much easier. Thanks ! – hackchoc Nov 30 '15 at 21:50
  • 1
    `-d` isn't really for existence, and the result could be "exist but not directory". More granular control: `ssh user@host 'function exist_and_is_dir { [[ -d $1 ]] && echo "exists and is directory" || { [[ -e $1 ]] && echo "exists but is not directory" || echo "does not exist"; }; }; exist_and_is_dir Downloads`. – 4ae1e1 Nov 30 '15 at 21:52
  • 1
    @hackchoc If you just `ssh armand@127.0.0.1 '[ -d Documents ]'`, assuming `ssh` is successful then the return code is either 0 or 1, where 0 is for exists and is a directory, and 1 is for anything else. So use `subprocess.check_call` to raise an exception when it returns 1. – 4ae1e1 Nov 30 '15 at 21:53
  • @hackchoc I updated the answer to show storing the answer in a variable – Eric Renouf Nov 30 '15 at 22:06
  • 2
    @hackchoc: the "variable" will be the exit status of `ssh`: 0 if it exists, 1 if it's not a directory, 255 if ssh failed – Andrea Corbellini Nov 30 '15 at 22:19
  • Great, thank you all for your help and your contribution ! :) – hackchoc Nov 30 '15 at 22:25