Bash snippets & functions : Find the greater / lower number


One more post in the “Bash snippets and functions” series.

This one was born a day i had the need for some way to find the greater (or the lower) from a list of random numbers. I needed this for another function i put in my bash_rc that allow me to add a persistent route from command line.


More “bash snippets & functions” posts


1 Description

This simple function take one or more numbers (integers) as arguments and return the greater (or lesser).

1.1 Limitations

This can only handles integers (as do bash). Floating point should be possible but i don’t need it so …

2 The code


# Find the greater from numbers given as arguments

FindGreater() {
  local numbers=( "${@}" )              # Initialize the array with given arguments
  local lenght="${#numbers[@]}"         # Get the number of elem in array
  local num="0"
  while (( num < "${lenght}" )) ; do

    if [[ "${numbers[$num]}" -ge "${greater:-0}" ]] ; then
      local greater="${numbers[$num]}"

  echo "Greater is : \"${greater}\""



3 Example

# Usage example in standalone mode (e.g from inside your bash_rc)
pier@test_machine:~$ FindGreater 0 1 0 2 3 444 333 100 0 0 
Greater is : "444"

# Usage example in script mode 
# (e.g from a script containing only this and called with the list of numbers to be compared)
FindGreater ${@}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site supports SyntaxHighlighter via WP SyntaxHighlighter. It can highlight your code.
How to highlight your code: Paste your code in the comment form, select it and then click the language link button below. This will wrap your code in a <pre> tag and format it when submitted.