check if file exists on remote host with ssh

后端 未结 11 719
醉酒成梦
醉酒成梦 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:31

    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
    
    0 讨论(0)
  • 2021-01-31 03:35

    This also works :

    if ssh user@ip "[ -s /path/file_name ]" ;then 
      status=RECEIVED ; 
     else 
      status=MISSING ; 
     fi
    
    0 讨论(0)
  • 2021-01-31 03:43

    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
    
    0 讨论(0)
  • 2021-01-31 03:43

    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.

    0 讨论(0)
  • Can't get much simpler than this :)

    ssh host "test -e /path/to/file"
    if [ $? -eq 0 ]; then
        # your file exists
    fi
    

    As suggested by dimo414, this can be collapsed to:

    if ssh host "test -e /path/to/file"; then
        # your file exists
    fi
    
    0 讨论(0)
提交回复
热议问题