I have an array in Bash, for example:
array=(a c b f 3 5)
I need to sort the array. Not just displaying the content in a sorted way, but to get a new array with the sorted elements. The new sorted array can be a completely new one or the old one.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You don’t really need all that much code:
Supports whitespace in elements (as long as it’s not a newline), and works in Bash 3.x.
e.g.:
Note: @sorontar has pointed out that care is required if elements contain wildcards such as
*or?:What’s happening:
The result is a culmination six things that happen in this order:
IFS=$'\n'"${array[*]}"<<<sortsorted=($(...))unset IFSFirst, the
IFS=$'\n'This is an important part of our operation that affects the outcome of 2 and 5 in the following way:
Given:
"${array[*]}"expands to every element delimited by the first character ofIFSsorted=()creates elements by splitting on every character ofIFSIFS=$'\n'sets things up so that elements are expanded using a new line as the delimiter, and then later created in a way that each line becomes an element. (i.e. Splitting on a new line.)Delimiting by a new line is important because that’s how
sortoperates (sorting per line). Splitting by only a new line is not-as-important, but is needed preserve elements that contain spaces or tabs.The default value of
IFSis a space, a tab, followed by a new line, and would be unfit for our operation.Next, the
sort <<<"${array[*]}"part<<<, called here strings, takes the expansion of"${array[*]}", as explained above, and feeds it into the standard input ofsort.With our example,
sortis fed this following string:Since
sortsorts, it produces:Next, the
sorted=($(...))partThe
$(...)part, called command substitution, causes its content (sort <<<"${array[*]}) to run as a normal command, while taking the resulting standard output as the literal that goes where ever$(...)was.In our example, this produces something similar to simply writing:
sortedthen becomes an array that’s created by splitting this literal on every new line.Finally, the
unset IFSThis resets the value of
IFSto the default value, and is just good practice.It’s to ensure we don’t cause trouble with anything that relies on
IFSlater in our script. (Otherwise we’d need to remember that we’ve switched things around–something that might be impractical for complex scripts.)