source: trunk/essentials/app-shells/bash/examples/functions/sort-pos-params

Last change on this file was 3228, checked in by bird, 19 years ago

bash 3.1

File size: 992 bytes
Line 
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.
4sort_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
31set -- 3 1 4 1 5 9 2 6 5 3 2
32sort_posparams "$@"
33
34# sets without preserving quoted parameters
35set -- $( sort_posparams "$@" )
36echo "$@"
37echo $#
38
39# sets preserving quoted parameters, beware pos params with embedded newlines
40set -- 'a b' 'a c' 'x z'
41
42oifs=$IFS
43IFS=$'\n'
44set -- $( sort_posparams "$@" )
45IFS="$oifs"
46
47echo "$@"
48echo $#
49
50sort_posparams
Note: See TracBrowser for help on using the repository browser.