我正在尝试比较一些文件,并做一些不同的事情。但是当与sh -c结合使用时,diff不能返回正确的退出代码。
root@i-qqixe8m2:~# cat /tmp/1
1
root@i-qqixe8m2:~# cat /tmp/2
2
root@i-qqixe8m2:~# set +x # Edited: useless cmd. But still kept here since answer below by @iBug would refer to this.
root@i-qqixe8m2:~# sh -c "diff /tmp/1 /tmp/2; echo $?;"
1c1
< 1
---
> 2
0
root@i-qqixe8m2:~# diff /tmp/1 /tmp/2; echo $?;
1c1
< 1
---
> 2
1
root@i-qqixe8m2:~#
PS。我在这里发现了相关的问题:git diff and bash return code,但没有提供任何理由,下面的评论我认为不是真正正确的解决方案,因为我在这里不使用git。
发布于 2019-05-06 10:16:20
因为您使用的是双引号,所以您当前的shell已经扩展了$?
,而不是sh
sh -c "diff /tmp/1 /tmp/2; echo $?;"
sh
看到的是第二个命令是echo 0
(最后一个命令set +x
返回0)。
要修复此问题,请使用单引号来防止当前$?
展开,以便sh
可以正确处理:
sh -c 'diff /tmp/1 /tmp/2; echo $?;'
或者干脆逃脱美元:
sh -c "diff /tmp/1 /tmp/2; echo \$?;"
使用set -x
调试外壳命令是一个很好的做法,我不确定为什么要使用+x
。
~ $ sh -c 'diff 1 2; echo $?;'
+ sh -c 'diff 1 2; echo $?;'
1c1
< 1
---
> 2
1
~ $ sh -c "diff 1 2; echo $?;"
+ sh -c 'diff 1 2; echo 0;'
1c1
< 1
---
> 2
0
~ $
请注意以+
开头的两行代码,这是您的shell实际执行的代码。
https://stackoverflow.com/questions/55997989
复制相似问题