Keep arrival order inside equal GNU sort keys
A job list sorted by priority may need to preserve arrival order among jobs with the same priority. Specifying a key alone does not guarantee that: GNU sort normally uses the entire line to break ties.
Run the example
Tested on Linux with GNU Bash 5.2.37, coreutils 9.7, grep 3.11 and diffutils 3.10. Use one Bash session and a text editor. Create a disposable working directory before saving the source:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Save as demo_linux_sort_stable_key_order.sh:
set -euo pipefail
export LC_ALL=C
records=$'2 zebra\n1 first\n2 alpha'
printf 'Default tie break:\n'
printf '%s\n' "$records" | sort -k1,1n
printf 'Stable key order:\n'
printf '%s\n' "$records" | sort -s -k1,1nRun it:
bash demo_linux_sort_stable_key_order.shObserved output:
Default tie break:
1 first
2 alpha
2 zebra
Stable key order:
1 first
2 zebra
2 alpha-k1,1n limits the numeric key to field one. -s disables the final whole-line comparison, leaving equal-priority records in input order. In the stable result, zebra stays ahead of alpha because it arrived first.
Limits and input policy
Stability preserves the order actually supplied to this invocation. If several producers interleave their output unpredictably, stable sorting cannot reconstruct an earlier global arrival order. Record a sequence number when that order must survive collection. Default fields use whitespace; use a format-aware parser for quoted CSV.
Clean up
Remove the saved script and the empty working directory in the same Bash session:
rm -- demo_linux_sort_stable_key_order.sh
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf the directory is not empty, inspect its contents before removing anything else.
Reference
Acknowledgements
This post was created with assistance from AI.