zsh:
print -r -- ${(Oa)=VAR}
$=VAR splits $VAR on $IFS. (Oa) orders the resulting list in reverse array order. print -r -- (like in ksh), same as echo -E - (zsh specific) is a reliable versions of echo: prints its arguments as-is separated by space, terminated by newline.
If you want to split on space only, and not on whatever $IFS contains (space, tab, newline, nul by default), either assign space to $IFS, or use an explicit splitting like:
print -r -- ${(Oas: :)VAR}
To sort in reverse numerical order:
$ VAR='50 10 20 90 100 30 60 40 70 80' $ print -r -- ${(nOn)=VAR} 100 90 80 70 60 50 40 30 20 10
POSIXly (so would also work with bash):
With shell builtin (except for printf in some shells) mechanisms only (better for variables with a short value):
unset -v IFS # restore IFS to its default value of spc, tab, nl set -o noglob # disable glob set -- $VAR # use the split+glob operator to assign the words to $1, $2... reversed_VAR= sep= for i do reversed_VAR=$i$sep$reversed_VAR sep=' ' done printf '%s\n' "$reversed_VAR"
With awk (better for large variables, especially with bash, but up to the limit of the size of the arguments (or of a single argument)):
awk ' BEGIN { n = split(ARGV[1], a); while (n) {printf "%s", sep a[n--]; sep = " "} print "" }' "$VAR"