Check if directory exists on remote machine with s

2020-08-27 01:04发布

问题:

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.

回答1:

This is a one liner:

ssh armand@127.0.0.1 '[ -d Documents ] && echo exists || echo does not exist'


回答2:

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



标签: bash ssh