check if file exists on remote host with ssh

2019-03-09 17:30发布

I would like to check if a certain file exists on the remote host. I tried this:

$ if [ ssh user@localhost -p 19999 -e /home/user/Dropbox/path/Research_and_Development/Puffer_and_Traps/Repeaters_Network/UBC_LOGS/log1349544129.tar.bz2 ] then echo "okidoke"; else "not okay!" fi
-sh: syntax error: unexpected "else" (expecting "then") 

10条回答
放我归山
2楼-- · 2019-03-09 17:51

You're missing ;s. The general syntax if you put it all in one line would be:

if thing ; then ... ; else ... ; fi

The thing can be pretty much anything that returns an exit code. The then branch is taken if that thing returns 0, the else branch otherwise.

[ isn't syntax, it's the test program (check out ls /bin/[, it actually exists, man test for the docs – although can also have a built-in version with different/additional features.) which is used to test various common conditions on files and variables. (Note that [[ on the other hand is syntax and is handled by your shell, if it supports it).

For your case, you don't want to use test directly, you want to test something on the remote host. So try something like:

if ssh user@host test -e "$file" ; then ... ; else ... ; fi
查看更多
我想做一个坏孩纸
3楼-- · 2019-03-09 17:52

Can't get much simpler than this :)

ssh host "test -e /path/to/file"
if [ $? -eq 0 ]; then
    # your file exists
fi
查看更多
在下西门庆
4楼-- · 2019-03-09 17:52

one line, proper quoting

ssh remote_host test -f "/path/to/file" && echo found || echo not found
查看更多
劳资没心,怎么记你
5楼-- · 2019-03-09 17:55

Test if a file exists:

HOST="example.com"
FILE="/path/to/file"

if ssh $HOST "test -e $FILE"; then
    echo "File exists."
else
    echo "File does not exist."
fi

And the opposite, test if a file does not exist:

HOST="example.com"
FILE="/path/to/file"

if ! ssh $HOST "test -e $FILE"; then
    echo "File does not exist."
else
    echo "File exists."
fi
查看更多
戒情不戒烟
6楼-- · 2019-03-09 17:56

On CentOS machine, the oneliner bash that worked for me was:

if ssh <servername> "stat <filename> > /dev/null 2>&1"; then echo "file exists"; else echo "file doesnt exits"; fi

It needed I/O redirection (as the top answer) as well as quotes around the command to be run on remote.

查看更多
太酷不给撩
7楼-- · 2019-03-09 17:58

Here is a simple approach:

if ssh $HOST stat $FILE_PATH \> /dev/null 2\>\&1
            then
                    echo "File exists"
            else
                    echo "File does not exist"

fi
查看更多
登录 后发表回答