What you are looking for is a Version Sort, which exists in various executables. Another tool that would fit the bill is sort
. However, since your values are contained in variables and not in a list of numbers, sort -t : -k 1.1n,2.2n,3.3n filename
is of little use unless you want to write the values out to a temp file and sort
them returning the results in an array (a good idea). Be that as it may, you can implement a short sort based on your v1
and v2
that will serve the purpose:
#!/bin/bash
[ -n "$1" ] && [ -n "$2" ] || {
printf "Error: insufficient input. Usage: %s ver_num1 ver_num2\n" "${0//*\//}"
exit 1
}
v1="$1" # v1
v2="$2" # v2
v1s=$v1 # saved copies of complete string
v2s=$v2 # (same for v2)
[ "$v1" = "$v2" ] && # test inputs are equal and exit
echo "$v1 = $v2" &&
exit 0
while :; do
tv1=${v1%%.*} # tmpv1 stores the first number for v1
tr1=${v1#*.} # trv1 stores the remaining digits for v1
tv2=${v2%%.*} # (same for v2)
tr2=${v2#*.}
if [ "$tv1" = "" ] || [ "$tv2" = "" ]; then # if different length and
[ -n "$tv1" ] && echo "$v1s > $v2s" && break # equal at this point
[ -n "$tv2" ] && echo "$v1s < $v1s" && break # longer string wins
fi
if [ "$tv1" -gt "$tv2" ]; then # test 1st digit
echo "$v1s > $v2s" && break # if > or <, output results and break
elif [ "$tv1" -lt "$tv2" ]; then
echo "$v1s < $v2s" && break
else # if no determination, go to next digit
v1=$tr1 # set v1, v2 to remaining digits to loop again
v2=$tr2
fi
done
exit 0
output:
$ bash 3waySort.sh 3.2.2 3.2.3
3.2.2 < 3.2.3
$ bash 3waySort.sh 3.2.3 3.2.3
3.2.3 = 3.2.3
$ bash 3waySort.sh 3.2 3.2.3
3.2 < 3.2.3
$ bash 3waySort.sh 1.2.4.7 3.2.3
3.2.3 > 1.2.4.7
Note: I've added a few additional test and set the values to be passed as arg1
and arg2
to get you started.