summaryrefslogtreecommitdiff
path: root/examples/functions/sort-pos-params
diff options
context:
space:
mode:
authorAn-Cheng Huang <ancheng@vyatta.com>2007-11-12 13:06:02 -0800
committerAn-Cheng Huang <ancheng@vyatta.com>2007-11-12 13:06:02 -0800
commitb7fc9e0f6d6105ba2203f219743d4b269415e84b (patch)
treeef6586dfc62798c2b17487b443864699aca55f31 /examples/functions/sort-pos-params
downloadvyatta-bash-b7fc9e0f6d6105ba2203f219743d4b269415e84b.tar.gz
vyatta-bash-b7fc9e0f6d6105ba2203f219743d4b269415e84b.zip
initial import from bash_3.1dfsg.orig.tar.gz
Diffstat (limited to 'examples/functions/sort-pos-params')
-rw-r--r--examples/functions/sort-pos-params50
1 files changed, 50 insertions, 0 deletions
diff --git a/examples/functions/sort-pos-params b/examples/functions/sort-pos-params
new file mode 100644
index 0000000..0052b46
--- /dev/null
+++ b/examples/functions/sort-pos-params
@@ -0,0 +1,50 @@
+# Sort the positional paramters.
+# Make sure the positional parameters are passed as arguments to the function.
+# If -u is the first arg, remove duplicate array members.
+sort_posparams()
+{
+ local -a R
+ local u
+
+ case "$1" in
+ -u) u=-u ; shift ;;
+ esac
+
+ # if you want the case of no positional parameters to return success,
+ # remove the error message and return 0
+ if [ $# -eq 0 ]; then
+ echo "$FUNCNAME: argument expected" >&2
+ return 1
+ fi
+
+ # make R a copy of the positional parameters
+ R=( "${@}" )
+
+ # sort R.
+ R=( $( printf "%s\n" "${R[@]}" | sort $u) )
+
+ printf "%s\n" "${R[@]}"
+ return 0
+}
+
+# will print everything on separate lines
+set -- 3 1 4 1 5 9 2 6 5 3 2
+sort_posparams "$@"
+
+# sets without preserving quoted parameters
+set -- $( sort_posparams "$@" )
+echo "$@"
+echo $#
+
+# sets preserving quoted parameters, beware pos params with embedded newlines
+set -- 'a b' 'a c' 'x z'
+
+oifs=$IFS
+IFS=$'\n'
+set -- $( sort_posparams "$@" )
+IFS="$oifs"
+
+echo "$@"
+echo $#
+
+sort_posparams