sid*_*com 56 bash shell diff exit-code
在diff
手册页上我找到了这些退出值:
0 No differences were found.
1 Differences were found.
>1 An error occurred.
Run Code Online (Sandbox Code Playgroud)
对于不同的错误,是否有不同的退出值高于1?
Fré*_*idi 59
这取决于你的diff
命令.我的(GNU diffutils 3.0)说:
退出状态
0
意味着没有发现差异,1
意味着发现了一些差异,并且2
意味着麻烦.通常情况下,不同的二进制文件算不算麻烦,但可以通过改变-a
或--text
选项,或-q
或--brief
选项.
可能,或者可能没有不同的错误代码,具体取决于您使用的差异版本.如果我没记错的话,标准BSD diff总是会返回0,1或2的退出代码.
但是,联机帮助页没有映射diff可能执行的所有操作,但是可以使用文档来使用diff命令.在shell脚本中,我想知道文件是匹配的(exit = 0)还是不匹配(exit = 1).但是,在我的shell脚本中,我也想知道diff命令本身不起作用.
diff $file1 file2 > /dev/null 2>&1
error=$?
if [ $error -eq 0 ]
then
echo "$file1 and $file2 are the same file"
elif [ $error -eq 1 ]
then
echo "$file1 and $file2 differ"
else
echo "There was something wrong with the diff command"
fi
Run Code Online (Sandbox Code Playgroud)
想象一下,如果我被告知2意味着diff命令失败,但是更新版本的diff命令区分了一个你无法读取的文件(exit = 2)和一个丢失的文件(exit = 3).现在,假设我在早期版本的diff命令中执行了以下操作,但$file2
不存在:
diff $file1 file2 > /dev/null 2>&1
error=$?
if [ $error -eq 2 ]
then
echo "There was something wrong with the diff command"
elif [ $error -eq 1 ]
then
echo "$file1 and $file2 differ"
else
echo "$file1 and $file2 are the same file"
fi
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我检查了错误代码2和1,但没有检查3.因此,我假设文件匹配,而不是检测丢失的文件.
该联机帮助页正在尝试确保将来升级到操作系统不会导致大多数shell脚本突然失败.这就是为什么有一个独立的awk
,并nawk
命令和一个单独的grep
和egrep
命令.
*根据@chus的评论更新.