How to sort an array of strings in linux bash shell?

For example, an array

link2_pathname
link1_pathname
link3_pathname

How to get an array as shown below.

link1_pathname
link2_pathname
link3_pathname

Many thanks!

+4
source share
2 answers

cycle up to sort.

a=(l2 l3 l1)
b=($(for l in ${a[@]}; do echo $l; done | sort))

you probably need to keep an eye on IFS when handling string values ​​containing spaces.

+3
source

try it

var=( link2_pathname link1_pathname link3_pathname )

for arr in "${var[@]}"
do
    echo $arr
done | sort

new_var=( $(for arr in "${var[@]}" 
do
        echo $arr
done | sort) )
+1
source

All Articles