check if file exists on remote host with ssh

后端 未结 11 946
醉酒成梦
醉酒成梦 2021-01-31 03:20

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_Devel         


        
11条回答
  •  臣服心动
    2021-01-31 03:28

    You can specify the shell to be used by the remote host locally.

    echo 'echo "Bash version: ${BASH_VERSION}"' | ssh -q localhost bash
    

    And be careful to (single-)quote the variables you wish to be expanded by the remote host; otherwise variable expansion will be done by your local shell!

    # example for local / remote variable expansion
    {
    echo "[[ $- == *i* ]] && echo 'Interactive' || echo 'Not interactive'" | 
        ssh -q localhost bash
    echo '[[ $- == *i* ]] && echo "Interactive" || echo "Not interactive"' | 
        ssh -q localhost bash
    }
    

    So, to check if a certain file exists on the remote host you can do the following:

    host='localhost'  # localhost as test case
    file='~/.bash_history'
    if `echo 'test -f '"${file}"' && exit 0 || exit 1' | ssh -q "${host}" sh`; then
    #if `echo '[[ -f '"${file}"' ]] && exit 0 || exit 1' | ssh -q "${host}" bash`; then
       echo exists
    else
       echo does not exist
    fi
    

提交回复
热议问题