Linux sort: Why 10 Comes Before 2 and How to Fix It

Linux sort can make a duration report look wrong. Suppose it lists a 10-second job ahead of a 2-second job. Both values are correct. The surprise is that plain sort compares text. In the C locale, the first character of 10 comes before the first character of 2. For a file containing one number per line, use sort -n. For a report with job names in the first column and durations in the second, use sort -k2,2n.

Balanced brass weights with different tags illustrate equal numeric keys in Linux sort.

Linux sort with three numbers

These examples use GNU Coreutils. On a Linux system, run sort --version to identify your implementation before trying the GNU-specific debug option.

Run these two commands in a Linux shell. Each prints its result directly to the terminal.

printf '%s\n' 2 10 1 | LC_ALL=C sort

Output, one value per line: 1 → 10 → 2. The initial 1 puts both 1 and 10 ahead of 2.

printf '%s\n' 2 10 1 | LC_ALL=C sort -n

Numeric output: 1 → 2 → 10. The input is identical in both commands. Setting LC_ALL=C on each invocation makes the example reproducible across machines with different language settings. It also gives these commands a period as the decimal separator.

Sort a duration report by its second column

Suppose each row records a stage name and its duration in seconds. The two stages that took two seconds appear in execution order. Keep that order so a teammate can still follow the run.

printf '%s\n' 'package 10' 'test 2' 'lint 2' 'deploy 30' |
  LC_ALL=C sort -s -k2,2n

Expected output

test 2
lint 2
package 10
deploy 30

Read -k2,2n as “start at field two, end at field two, compare it numerically.” The -s keeps equal-duration rows in their original order. Try dropping it. GNU sort breaks the tie by comparing the complete lines, so lint moves ahead of test. If the report should show the slowest stage first, change the key to -k2,2nr and keep -s.

When adding -n still gives a surprising result

Every row starts with a name. Running sort -n on the stage report starts the numeric comparison at the beginning of the line. Each name has an empty numeric prefix, which GNU sort treats as zero. The fallback comparison can make the report look alphabetized. Select the duration field explicitly.

Linux sort –debug: Find the field being compared

A build report exported with vertical bars can still contain spaces inside job names. Paste this small example into your shell. The function prints the same two records each time so you can change one setting and see its effect.

stages() {
  printf '%s\n' 'build assets|12|ok' 'test suite|3|ok'
}
stages | LC_ALL=C sort --debug -s -k2,2n

With the default whitespace separator, field two starts with assets or suite. Neither starts with a number. Look for the missing numeric match in the annotations. Both keys compare equal, so stable sorting leaves the 12-second job first.

stages | LC_ALL=C sort --debug -s -t '|' -k2,2n
Linux sort sees assets|12|ok with whitespace splitting and 12 with a pipe delimiter.

Now find the underline beneath 3 and 12. The test stage moves to the top because the second field begins immediately after the first vertical bar. To print just the two ranked rows, remove --debug.

Which Linux sort option handles exponents and version names?

The values have extra syntax. A duration of 1e3 means 1,000 seconds, but -n reads its numeric prefix as 1. Use GNU sort -g for scientific notation. For names such as run-2 and run-10, try sort -V. If a duration column mixes seconds and milliseconds, convert every value to the same unit before ranking the jobs.

Linux sort with equal numeric keys

Two jobs both took two seconds. Which should appear first? If the report promises arrival order for ties, check it with a pair whose labels run backwards alphabetically.

export LC_ALL=C
printf 'zeta 2\nalpha 2\nmoss 10\n' | sort -k2,2n
printf 'zeta 2\nalpha 2\nmoss 10\n' | sort -s -k2,2n

In the first result, alpha 2 precedes zeta 2. Both numeric keys equal 2, and the whole-line comparison breaks the tie. In the second result, zeta 2 stays first. The stable sort option -s preserves input order for ties. Both commands place moss 10 last.

If your report promises alphabetical order for ties, spell that rule out with sort -k2,2n -k1,1. A reviewer can then tell which field decides each position.

Check Linux sort order without rewriting the report

Try a deliberately misordered pair before checking your own file:

printf '%s\n' 'package 10' 'test 2' | LC_ALL=C sort -s -c -k2,2n
printf 'exit status: %s\n' "$?"

The diagnostic identifies line 2, test 2, and the status is 1. Reverse the two quoted rows and run both commands again. This time the checker stays quiet and the printed status is 0. Read the status immediately after the pipeline, since the next shell command replaces it.

If your headerless, whitespace-delimited report is saved as durations.txt, the following command checks ascending duration order and allows ties in either order.

LC_ALL=C sort -s -c -k2,2n durations.txt

A correctly ordered file produces no output and returns status 0. Move package 10 above test 2 in a practice copy and repeat the check. GNU sort reports the first row that breaks the ordering and returns status 1. This checks ordering only. A missing duration can still compare as zero, so check for empty fields separately if the report comes from an export.

One final detail matters when counting jobs. Adding -u to the numeric-key sort can collapse test 2 and lint 2 into a single row. Both jobs belong in this report. For the related problem of identifying repeated lines, see why uniq leaves duplicate lines in Linux.

Apply the checks to a real report

A useful Linux sort test file contains at least one row that would land in the wrong place under a text comparison and two rows that tie. The three numbers at the top of this guide cover the first case. The build stages cover both. Before using a longer pipeline, choose a pair of records whose relative order you can predict. If those two come out backwards, inspecting the key is quicker than scrolling through a thousand rows.

Keep the header above Linux sort output

A report exported by another tool may begin with a header. Sorting that row with the data makes the result depend on how its label compares. For example, a numeric key beginning with seconds compares as zero. That can look correct with positive durations and fail as soon as the same procedure is used on a column containing negative values.

printf '%s\n' 'stage|seconds' 'package|10' 'test|2' |
  ( IFS= read -r header && printf '%s\n' "$header"
    LC_ALL=C sort -s -t '|' -k2,2n )

In this Linux sort pipeline, the parenthesized commands share one input stream. The first reads and prints one header. The second receives the remaining records. The result starts with stage|seconds, followed by test|2 and package|10. Use this recipe when the input always has exactly one header. On a headerless file it would preserve the first data row in place regardless of its value.

Break ties with a second Linux sort key

Preserving arrival order is helpful for a build log. A weekly summary may instead need a repeatable alphabetical order among jobs with the same duration, even when the exporter changes the order of the input. Add a second key after the numeric one. Put the rule for the most important comparison first.

printf '%s\n' 'test|2' 'package|10' 'lint|2' |
  LC_ALL=C sort -t '|' -k2,2nr -k1,1
Stable Linux sort preserves test before lint. A secondary name key puts lint first.

Expect package|10, then lint|2, then test|2. The r attached to field two reverses the duration ranking. Field one still goes forward. A global reverse option would express a different intention. When reviewing a Linux sort command, ask which job should win a tie before choosing between a stable sort and an explicit second key.

Check for missing values before running Linux sort

Consider three durations written as 0, a blank, and unknown. Only the first records a measurement. A numeric comparison can still put all three together. An order check can succeed on that output, so it helps to test the input format independently.

printf '%s\n' 'test|2' 'lint|' 'package|unknown' 'deploy|0' |
  LC_ALL=C awk -F '|' '$2 !~ /^[0-9]+([.][0-9]+)?$/ {print NR, $0}'

This example accepts nonnegative whole seconds or a decimal such as 2.5. It prints 2 lint| and 3 package|unknown. The zero-duration deployment passes. If your instrument uses signed measurements, scientific notation, or a comma decimal separator, define that format first and adapt the check. A missing reading and a measured zero answer different questions.

Choose a Linux sort option for your units

Suppose a report contains 900ms and 2s. Comparing the numeric prefixes alone puts 2 before 900. In elapsed time, the 900-millisecond task finishes first. Export both values in milliseconds, retaining the original units in a separate field if someone needs to audit the conversion. The numbers to compare are now 900 and 2000.

Versioned filenames present a different problem. In run-10.log the number sits inside a label. Here is a quick way to see the effect of choosing version order:

printf '%s\n' run-10.log run-2.log run-1.log | LC_ALL=C sort -V

Expect the runs numbered 1, 2, and 10. Use this for labels with digit sequences. A decimal measurement such as 1.10 seconds has its own meaning: it equals 1.1 seconds. A version identifier such as release 1.10 can follow release 1.2. Decide what the field represents before picking the switch.

Interpret the Linux sort exit status

GNU sort check status: 0 for ordered input, 1 for disorder and 2 for an error.

For GNU sort -c, status 0 means the input met the specified ordering rule, and status 1 means a disorder was found. Status 2 signals an error such as an unreadable input. Treating every nonzero result as an out-of-order file can send you looking for a bad record in a file the command never opened. Keep the diagnostic alongside the status when investigating a failed scheduled report.

When saving a reordered report, send the result to a new filename. A command such as sort -n numbers.txt > numbers.txt lets the shell truncate the source before the sorter reads it. Check the new output with the same delimiter, locale, and key options that produced it. That check is meaningful only for the ordering rule you actually intend to enforce.

What if the file has quoted CSV fields?

Look at one complete record before using a comma as the field separator. A job named build, package can appear inside quotes, with another comma after the closing quote. A simple delimiter split treats both commas alike. The field number in the file you see can therefore differ from the column you see in a spreadsheet.

For CSV exports, use a CSV-aware reader to extract the numeric column or export the two required columns into a simpler format. The following self-contained Python 3 example reads a header and sorts two records by elapsed seconds. It prints a CSV header and quotes the comma-containing job name on output.

python3 - <<'PY'
import csv
import io
import sys
from decimal import Decimal

sample = 'stage,seconds\n"build, package",10\ntest,2\n'
rows = csv.DictReader(io.StringIO(sample))
writer = csv.DictWriter(sys.stdout, fieldnames=['stage', 'seconds'])
writer.writeheader()
writer.writerows(sorted(rows, key=lambda row: Decimal(row['seconds'])))
PY

The first data row in the result is test,2. The final row retains the quotation marks around the stage name. The example assumes the duration column contains valid decimals and the data fits in memory. For the plain pipe-delimited examples above, the shorter Linux sort pipeline is sufficient.

Does reversing the result also reverse equal rows?

Try a prediction before running the next example. A report needs the longest job at the top. Two short jobs tied, and their start order matters to the person reading it. Where should the second short job appear?

printf '%s\n' 'first 2' 'slow 10' 'second 2' |
  LC_ALL=C sort -s -k2,2nr

Read down the output: slow 10, first 2, second 2. Reversing the numeric key changes which durations come first. The stable comparison still keeps the two tied jobs in arrival order. Sorting ascending and then reversing all the output lines would reverse those two jobs as well. This distinction matters when rows record events in sequence.

What should go in a reproducible Linux sort bug report?

Include the smallest input that demonstrates the problem, the exact command, the output you got, and the order you expected. State which field contains the measurement, its unit, and whether a tie should preserve input order. If two machines disagree, record the locale and the Coreutils version on each. The example at the top pins the locale so the comparison begins from the same conditions.

A report saying “sorting is broken” leaves the reader guessing whether the problem is the delimiter, the number format, or the tie rule. A report saying “the 12-second job precedes the 3-second job when field two is separated by a pipe” gives them a pair of rows and one specific setting to investigate.

Can a numeric sort make a job disappear?

Ordinary Linux sort keeps both rows when two jobs finish in the same number of seconds. The -u option changes what counts as a duplicate. Once you select a numeric key, two different records can have the same key. You can see the consequence using three input rows and counting how many survive each operation.

jobs() {
  printf '%s\n' 'lint 2' 'test 2' 'lint 2'
}
jobs | LC_ALL=C sort -s -k2,2n
jobs | LC_ALL=C sort -u -k2,2n
jobs | LC_ALL=C sort -u

The first pipeline returns three rows because all measurements are retained. The second returns one because all durations are equal. The third returns two because the two identical lint records collapse while the differently named test record survives. Decide whether you want one row per observation, one row per distinct duration, or one row per distinct line. The right answer depends on what you intend to count next.

Imagine a dashboard built from that second pipeline. It would report one job at two seconds even though the input contained three observations. Sorting can look correct on screen while the count used downstream becomes wrong. Include at least one repeated value and one repeated whole line in a test sample whenever a change introduces -u.

Why can a successful order check miss a lost row?

Take the two rows test 2 and package 10. If an upstream filter drops the first, the remaining single line still satisfies an ascending-order check. The check compares neighbors. With only one row there is no pair to contradict the rule. When every record matters, compare the input and output counts separately from the order check.

jobs | wc -l
jobs | LC_ALL=C sort -s -k2,2n | wc -l
jobs | LC_ALL=C sort -u -k2,2n | wc -l

Using the function above, the counts are three, three, and one. The sample generator terminates every record with a newline, so the newline count also gives the record count here. Equal counts alone still cannot detect a changed measurement: check the content of a representative row as well. The three checks answer different questions about a report: did all rows arrive, did the values survive, and are they in the requested order?

For a small handoff, attach the sample input along with those three expectations. A teammate can rerun the Linux sort command on another machine and pinpoint the first disagreement. If the row count already differs before sorting, investigating numeric flags will not explain the missing observation.

Linux sort quick reference for report editors

What the column containsComparison to useExample in ascending order
Elapsed seconds-n1.5, 2, 10
Scientific notation-g9e1, 1e2
Numbered filenames-Vrun-2, run-10
Fixed-width identifiers in the C localeDefault text order001, 002, 010

If leading zeros are part of an identifier, preserve them in the output. Numeric keys such as 2 and 002 compare equal. Whether they identify the same record is a decision for the application that produced the data.

For the full Linux sort option reference, see GNU Coreutils manual for sort.

Stay Updated with Kioptrix

Get practical guides, useful resources, and new articles delivered to your inbox.

No spam. Unsubscribe anytime. Read our Privacy Policy.