4

How can I take sort bash arguments alphabetically?

$ ./script.sh bbb aaa ddd ccc

and put it into an array such that I now have an array {aaa, bbb, ccc, ddd}

jaypal singh
  • 74,723
  • 23
  • 102
  • 147
ehaydenr
  • 240
  • 3
  • 13

3 Answers3

7

You can do:

A=( $(sort <(printf "%s\n" "$@")) )

printf "%s\n" "${A[@]}"
aaa
bbb
ccc
ddd

It is using steps:

  1. sort the arguments list i.e."$@"`
  2. store output of sort in an array
  3. Print the sorted array
anubhava
  • 761,203
  • 64
  • 569
  • 643
4

I hope following 2 lines will help.

sorted=$(printf '%s\n' "$@"|sort)

echo $sorted

This will give you a sorted cmdline args.I wonder though why its needed :)

But anyway it will sort your cmdlines

Removed whatever was not required.

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
PradyJord
  • 2,136
  • 12
  • 19
0

Here's an invocation that breaks all the other solutions proposed here:

./script.sh "foo bar" "*" "" $'baz\ncow'

Here's a piece of code that works correctly:

array=()
(( $# )) && while IFS= read -r -d '' var
do
  array+=("$var")
done <  <(printf "%s\0" "$@" | sort -z)
that other guy
  • 116,971
  • 11
  • 170
  • 194
  • I downvoted this because I don't know a lot of case where sorting long field with linebreak are really a need. In the other hand, I know a lot of cases where quick sort on small fields may be usefull. – F. Hauri - Give Up GitHub May 10 '14 at 00:10
  • @F.Hauri It was a poorly written question with no mention of edge cases. I would have down voted the question. – jaypal singh May 10 '14 at 00:14
  • @F.Hauri As long as you're doing it for fair and logical reasons and not petty childishness, I'm fine with that. – that other guy May 10 '14 at 00:16
  • @jaypal I agreee, and I won't downvote this answer at all because there is a real effort to present a reliable way of working with *null terminated strings*, but SO won't let me correct my vote now... – F. Hauri - Give Up GitHub May 10 '14 at 00:16