bash 如何通过SSH查找特定目录中存在的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5325332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:37:38  来源:igfitidea点击:

how to find a file exists in particular dir through SSH

bashssh

提问by Tree

how to find a file exists in particular dir through SSH

如何通过SSH查找特定目录中存在的文件

for example : host1 and dir /home/tree/TEST

例如:host1 和目录 /home/tree/TEST

Host2:- ssh host1 - find the TEST file exists or not using bash

Host2:- ssh host1 - 使用 bash 查找 TEST 文件是否存在

回答by Erik

ssh will return the exit code of the command you ask it to execute:

ssh 将返回您要求它执行的命令的退出代码:

if ssh host1 stat /home/tree/TEST \> /dev/null 2\>\&1
then 
  echo File exists
else 
  echo Not found
fi

You'll need to have key authentication setup of course, so you avoid the password prompt.

当然,您需要进行密钥身份验证设置,以免出现密码提示。

回答by mikeytown2

This is what I ended up doing after reading and trying out the stuff here:

这是我在阅读并尝试了这里的东西后最终做的事情:

FileExists=`ssh host "test -e /home/tree/TEST && echo 1 || echo 0"`

if [ ${FileExists} = 0 ]
  #do something because the file doesn't exist
fi

More info about test: http://linux.die.net/man/1/test

有关测试的更多信息:http: //linux.die.net/man/1/test

回答by Drew Anderson

An extension to Erik's accepted answer.

Erik 已接受答案的扩展。

Here is my bash script for waiting on an external process to upload a file. This will block current script execution indefinitely until the file exists.

这是我的 bash 脚本,用于等待外部进程上传文件。这将无限期地阻止当前脚本的执行,直到文件存在。

Requires key-based SSH access although this could be easily modified to a curl version for checks over HTTP.

需要基于密钥的 SSH 访问,尽管这可以很容易地修改为 curl 版本以通过 HTTP 检查。

This is useful for uploads via external systems that use temporary file names:

这对于通过使用临时文件名的外部系统上传非常有用:

  • rsync
  • transmission (torrent)
  • 同步
  • 传输(洪流)

Script below:

脚本如下:

#!/bin/bash
set -vx

#AUTH="user@server"
AUTH=""
#FILE="/tmp/test.txt"
FILE=""

while (sleep 60); do
    if ssh ${AUTH} stat "${FILE}" > /dev/null 2>&1; then
        echo "File found";
        exit 0;
    fi;
done;

回答by karni

No need for echo. Can't get much simpler than this :)

不需要回声。没有比这更简单的了:)

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