How to Add Options to Bash Function

Putting everything together here, I think this code will work for you:

export CATALINA_HOME=/tomcat/directory

function tomcat {
    if [ "$1" = "-s" ]; then
        sh $CATALINA_HOME/bin/startup.sh
    elif [ "$1" = "-x" ]; then
        sh $CATALINA_HOME/bin/shutdown.sh
    else
        echo "Enter '-s' to start Tomcat, '-x' to shutdown."
    fi
}

Important changes from your version:

  • Removed backquotes around startup and shutdown commands
  • Surrounded the $1 variable in double quotes

Some notes about bash syntax and safety:

  • function tomcat { is equivalent to tomcat() {
  • As @ooshro points out, a space is required after the [ after if -- when in doubt, space it out
  • in comparisons, you should prefer = over ==, as single-equals is the standard other shells use
  • always surround variables (like $1) in double quotes, especially in comparison statements, or anywhere where leaving them out would cause a problem
  • @ooshro's case syntax is a more concise way to deal with this problem, but it can be less flexible if you plan to make your code more complicated in the future
  • backquotes capture the output of a command and then replace it into the script, so if you surround an entire line with backquotes, bash will execute that line and then try to execute the output, which is rarely what you probably want
  • You don't need backquote functionality for this script, but when you do, I suggest using the $(...) syntax instead, as it's nestable and in my opinion far easier to read and understand

Try(error in the lack of space after '['):

export CATALINA_HOME=/tomcat/directory

tomcat() {
        case "$1" in
            -s) ${CATALINA_HOME}/bin/startup.sh;;
            -x) ${CATALINA_HOME}/bin/shutdown.sh;;
            *) "Enter '-s' to start Tomcat, '-x' to shutdown."
        esac
}

What do you mean with "does not work"? Do you get any error messages? What happens when you start your function?

Try putting a space always after and before the "[" and "]" .

Also quote $1 as "$1".

And "=" should be "==", so:

export CATALINA_HOME=/tomcat/directory

function tomcat {
   if [ "$1" == "-s" ]; then
      `sh $CATALINA_HOME/bin/startup.sh`
   elif [ "$1" == "-x" ]; then
      `sh $CATALINA_HOME/bin/shutdown.sh`
   else
      echo "Enter '-s' to start Tomcat, '-x' to shutdown."
   fi
}

works for me.