Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash : Check if file is sorted with sort -c file

Tags:

bash

sorting

With

sort -c file

I received the first bad line that is unsorted as report, or nothing if the file is sorted. (And sort -c do not sort the file.)

I want to check if I received a report or not. Something going like this :

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

Is it possible, and how ?

Same question with -C instead of -c (if it's different or not with the "silent" option)...

like image 568
Emerald Cottet Avatar asked Dec 01 '22 10:12

Emerald Cottet


2 Answers

Here's the same concept, just with a little syntactic sugar.

sort -C file || echo -n "not " ; echo "sorted"

I prefer the format that Cyrus used, I just wanted to provide a fun version.

Here is a posix compliant version (as suggested by anishsane):

sort -C file || printf "not " ; echo "sorted"
like image 102
Mark Avatar answered Dec 04 '22 05:12

Mark


if sort -C file; then
  # return code 0
  echo "sorted"
else
  # return code not 0
  echo "not sorted"
fi
like image 33
Cyrus Avatar answered Dec 04 '22 03:12

Cyrus