0052b466122965f6b95374ee9c182e20e0b1c105
[platform/upstream/bash.git] / examples / functions / sort-pos-params
1 # Sort the positional paramters.
2 # Make sure the positional parameters are passed as arguments to the function.
3 # If -u is the first arg, remove duplicate array members.
4 sort_posparams()
5 {
6         local -a R
7         local u
8
9         case "$1" in
10         -u)     u=-u ; shift ;;
11         esac
12
13         # if you want the case of no positional parameters to return success,
14         # remove the error message and return 0
15         if [ $# -eq 0 ]; then
16                 echo "$FUNCNAME: argument expected" >&2
17                 return 1
18         fi
19
20         # make R a copy of the positional parameters
21         R=( "${@}" )
22
23         # sort R.
24         R=( $( printf "%s\n" "${R[@]}" | sort $u) )
25
26         printf "%s\n" "${R[@]}"
27         return 0
28 }
29
30 # will print everything on separate lines
31 set -- 3 1 4 1 5 9 2 6 5 3 2
32 sort_posparams "$@"
33
34 # sets without preserving quoted parameters
35 set -- $( sort_posparams "$@" )
36 echo "$@"
37 echo $#
38
39 # sets preserving quoted parameters, beware pos params with embedded newlines
40 set -- 'a b' 'a c' 'x z'
41
42 oifs=$IFS
43 IFS=$'\n'
44 set -- $( sort_posparams "$@" )
45 IFS="$oifs"
46
47 echo "$@"
48 echo $#
49
50 sort_posparams