Your solution tries to store the list items to the SortedList
before the sort itself. The echo $i
part sends the list to the pipe and the sort -nu
then prints it (sorted) to the STDOUT
. If you want to store the sorted list to the variable, just try this:
function Sort() {
SortedList=`for i in $list; do echo $i; done | sort -nu`
}
If you're wondering why the SortedList
variable is empty after the function call, the problem is the pipe to the sort
command. Without the pipe it works fine. From wiki:
In the most commonly used simple pipelines the shell connects a series of sub-processes via pipes, and executes external commands within each sub-process. Thus the shell itself is doing no direct processing of the data flowing through the pipeline.
That means the for
part of the pipe starts a new sub-process (with the sorted var initialized), that changes the sorted variable as it is supposed to. But, when the process ends, you are back in the environment with the initial value of the variable.
Also, consult this post (Set a parent shell's variable from a subshell)