Bash:检查文件是否使用 sort -c file 排序

Eme*_*tet 3 sorting bash

sort -c file
Run Code Online (Sandbox Code Playgroud)

我收到了第一个未排序的错误行作为报告,如果文件已排序,则什么也没有。(并且 sort -c 不对文件进行排序。)

我想检查我是否收到了报告。事情是这样的:

if [ $(sort -c file) == *something* ]
then
    echo wasn't sorted
    sort file
    ...
else
    echo already sorted
    ...
fi
Run Code Online (Sandbox Code Playgroud)

有可能吗,怎么可能?

与 -C 而不是 -c 的相同问题(如果与“静音”选项不同)...

Mar*_*ark 10

这是相同的概念,只是有一点语法糖。

sort -C file || echo -n "not " ; echo "sorted"
Run Code Online (Sandbox Code Playgroud)

我更喜欢 Cyrus 使用的格式,我只是想提供一个有趣的版本。

这是一个符合 posix 的版本(如 anishsane 所建议的):

sort -C file || printf "not " ; echo "sorted"
Run Code Online (Sandbox Code Playgroud)

  • 我很内疚,我也使用了 `echo -n`,但请注意 `echo -n` 是不可移植的。某些版本的 `echo` 不支持 `-n` 并按字面打印。如有疑问,请使用与 posix 兼容的 `printf "%s" "text"`。 (3认同)

Cyr*_*rus 7

if sort -C file; then
  # return code 0
  echo "sorted"
else
  # return code not 0
  echo "not sorted"
fi
Run Code Online (Sandbox Code Playgroud)