5

For instance, the array is

link2_pathname
link1_pathname
link3_pathname

How can I get the array like below.

link1_pathname
link2_pathname
link3_pathname

Thanks a lot in advance!

liam xu
  • 2,892
  • 10
  • 42
  • 65

2 Answers2

5

pipe a loop to sort.

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

you probably need to watch out for the IFS when handling string values containing spaces.

Marc Bredt
  • 905
  • 5
  • 13
  • thanks. I tested this script, why it output l2 when I echo $a. I want to output l2,l3,l1 – liam xu Jun 17 '15 at 03:20
  • i do not know bash's inner handling of the IFS when printing an array. `@` or `*` expand to all entries in an array. you might want to access or print the values contained by `echo ${a[@]}`. ${a} probably just returns l2 because the default IFS, which is a space is recocognized and therefor cut off due to uncomplete variable expansion. – Marc Bredt Jun 17 '15 at 10:50
3

try this

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) )
Dan
  • 74
  • 3