检查"diff"的输出.使用shell脚本的命令 [英] Checking the output of "diff" command using shell script

查看:123
本文介绍了检查"diff"的输出.使用shell脚本的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下命令将linux计算机上的文件与远程计算机(两个AWS实例)上的另一个文件进行比较:

I am comparing a file on my linux machine with another file on a remote machine (both AWS Instances) using the following command:

diff -s main <(ssh -i /home/ubuntu/sai_key.pem ubuntu@w.x.y.z 'cat /home/ubuntu/c1')

当两个文件相同时,我想编写一个shell脚本不做任何事情,而当Linux机器(主机)中的文件发生更改时,我想更新远程机器中的文件.

I want to write a shell script to do nothing when both files are same and update the file in the remote machine when the file in the linux machine (host) changes.

我希望Shell脚本每30秒检查一次远程文件.

I want the shell script to check the remote file every 30 seconds.

我仅在主机上运行shell脚本,而不在远程主机上运行.

I am running the shell script on my host machine only and not the remote one.

您能帮我吗?

推荐答案

首先,我建议使用cmp而不是diff(我相信它会更有效),但是该解决方案应该以任何一种方式起作用.

First of all, I would recommend using cmp rather than diff (I believe it is more efficient), but this solution should work either way.

您需要做的就是编写一个包含if语句的bash脚本.如果cmpdiff命令未返回任何内容,则无需执行任何操作.在其他情况下,您只需要将当前的main文件scp移到远程主机上即可.

All you need to do is write a bash script with an if statement in it. If the cmp or diff command returns nothing, you don't need to take any action. In the other case, you just need to scp your current main file over to the remote host.

如果您决定使用cmp,则if语句只需要看起来像:

If you decide to use cmp, that if statement just needs to look like:

if cmp -s main <(ssh -i /home/ubuntu/sai_key.pem ubuntu@w.x.y.z 'cat /home/ubuntu/c1')
then
    echo "Match!"
else
    echo "No match!"
    scp ...
fi

如果您真的不习惯使用diff,请在下面评论,我可以很快地写出等效的内容.

If you really are dead set on using diff, comment below and I can write something up really quick that does the equivalent.

每30秒检查一次远程文件(运行此bash脚本)可能会有些过头,但这实际上取决于您.要实现定期检查(这仅适用于1分钟以上的时间间隔),可以使用cron计划程序.我建议使用 Crontab大师来创建cron计划并了解它们的工作方式.出于您的目的,您只需要向crontab中添加一行(在终端中运行crontab -e以编辑crontab),如下所示:

Checking the remote file (running this bash script) every 30 seconds may be slightly overkill, but it's really up to you. To achieve a periodic check (this only works for time intervals above 1 minute), you could use a cron scheduler. I recommend using Crontab Guru to create cron schedules and understand how they work. For your purpose, you would just need to add one line to your crontab (in your terminal run crontab -e to edit your crontab) as follows:

* * * * * /absolute/path/to/shell/script.sh

还要确保您chmod拥有正确权限的脚本!

Make sure you chmod the script with the right permissions as well!

这篇关于检查"diff"的输出.使用shell脚本的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆