bash 如果两个文件不同,则 Shellscript 操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8139885/
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
Shellscript action if two files are different
提问by Spencer
I am importing a file to my server using this command:
我正在使用以下命令将文件导入我的服务器:
scp zumodo@shold:/test/test/test/server.py /test/test/test/test.py~/;
I want to restart my server if the newly imported file test.py~ differs from the test.py that already exists. How would I do this using a shellscript?
如果新导入的文件 test.py~ 与已经存在的 test.py 不同,我想重新启动我的服务器。我将如何使用 shellscript 做到这一点?
采纳答案by JRFerguson
You could diff() the two files. A return code of zero (0) means there are no differences. A return code of one (1) says the files differ.
你可以 diff() 这两个文件。零 (0) 的返回码表示没有差异。返回码一 (1) 表示文件不同。
回答by Andrew Schulman
if ! cmp test.py test.py~ >/dev/null 2>&1
then
# restart service
fi
Breaking that down:
打破它:
cmp test.py test.py~
returns true (0) if test.py and test.py~ are identical, else false (1). You can see this inman cmp
.!
inverts that result, so theif
statement translates to "if test.py and test.py~ are different".- The redirects
>/dev/null 2>&1
send all output ofcmp
to null device, so you just get the true/false comparison result, without any unwanted noise on the console.
cmp test.py test.py~
如果 test.py 和 test.py~ 相同,则返回 true (0),否则返回 false (1)。你可以在man cmp
.!
反转该结果,因此该if
语句转换为“如果 test.py 和 test.py~ 不同”。- 重定向
>/dev/null 2>&1
将所有输出发送cmp
到null device,因此您只会获得真/假比较结果,控制台上没有任何不需要的噪音。
回答by sorpigal
I'd do something like
我会做类似的事情
zumodo@shold$ cat /test/test/test/server.py | ssh zumodo@otherhost 'cat - > /test/test/test/test.py.new ; cmp /test/test/test/test.py /test/test/test/test.py.new || (mv /test/test/test/test.py.new /test/test/test/test.py ; echo issue restart command here)'