shell script – How to sort the list of positional parameters in POSIX sh


Is there a way to sort the list of positional parameters in POSIX sh? Each positional parameter could contain arbitrary characters (e.g. spaces, newlines, tabs, etc.). The sort algorithm should be general enough to sort the list based on any comparison defined by the programmer (e.g. numeric/lexicographical sorting using expr comparison, sorting that considers only a substring of each positional parameter, etc.).

It seems that POSIX sh’s list of positional arguments has the characteristics of both a stack and a queue. It supports push (set -- "$x" "$@"), pop (x="$1"; shift), enqueue (set -- "$@" "$x") and dequeue (x="$1"; shift) operations. However, there can only be a single list, which means that sorting must be done in-place and I cannot use common algorithms such as merge sort and quicksort.

Sample:

#!/bin/sh

set -- "Hello" "world" 9 8 7 "$(printf "0 \n")" "$(printf "1\t")"

# How do I sort the positional parameters above using comparison
# `expr "$x" \< "$y"` such that the result is the list below?
#
# "$(printf "0 \n")" "$(printf "1\t")" 9 8 7 "Hello" "world"

Note 1: I am looking for a POSIX solution that works for arbitrary positional arguments supplied by a user and arbitrary comparisons specified by the programmer.

Note 2: I am not trying to solve any practical problem. I have challenged myself to this sh sorting problem but I could not come up with a solution, so I am posting it here on Stack Exchange.



Source link

Leave a Comment