Sort & uniq in Linux shell

后端 未结 6 1605
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 10:41

What is the difference between the following to commands?

sort -u FILE

sort FILE | uniq
6条回答
  •  不知归路
    2021-01-30 11:04

    There is one slight difference: return code.

    The thing is that unless shopt -o pipefail is set the return code of the piped command will be return code of the last one. And uniq always returns zero (success). Try examining exit code, and you'll see something like this (pipefail is not set here):

    pavel@lonely ~ $ sort -u file_that_doesnt_exist ; echo $?
    sort: open failed: file_that_doesnt_exist: No such file or directory
    2
    pavel@lonely ~ $ sort file_that_doesnt_exist | uniq ; echo $?
    sort: open failed: file_that_doesnt_exist: No such file or directory
    0
    

    Other than this, the commands are equivalent.

提交回复
热议问题