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}

3
  • you already have them in $@ Commented May 9, 2014 at 21:22
  • Yes, but they aren't sorted. Commented May 9, 2014 at 21:23
  • yep its not, please check my Answer just to do tht :) Commented May 9, 2014 at 21:41

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

5 Comments

I don't understand the goal of 1st step: Why not simply declare -a A=($(sort <(printf "%s\n" "$@"))) ?
Sure that step can be eliminated, that is just for demonstration purpose. May I add that core of the answer is in 2nd step not 1st.
Users should be aware that this doesn't work with whitespace or special characters.
@rici It splits up the result based on IFS, which includes spaces by default.
@thatotherguy: sortargs() { mapfile -t $1 < <(printf "%s\n" "${@:2}"|sort); }; sortargs A "foo bar" "*" "" $'baz\tcow'; printf "%s\n" "${A[@]}". Still fails on newlines, of course.
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.

Comments

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)

4 Comments

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 It was a poorly written question with no mention of edge cases. I would have down voted the question.
@F.Hauri As long as you're doing it for fair and logical reasons and not petty childishness, I'm fine with that.
@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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.