11 April 2023

If condition and function with parameters in Bash

By umut

You can write own functions in terminal. I show you an example in zshrc in MacOs. You can use if you you use bashrc or zshrc in any os.

Function sample:

myFunction(){
  print($1)
}

Now if you write `myFunction umut` in terminal it’s print “umut”. If you want to one more parameter you can space and write new parameter and you can show that with $2

If condition is different than the most of other programming language. For example:

if [ $1 = "umut" ]; then
    echo $1 is here
fi

Now I want to install different version of java which are 11 and 1.8

export JAVA_HOME=/usr/bin/java

changeJava() {
  echo $1;
  if [ $1 = "11" ]; then
    export JAVA_HOME=/Users/umut/Library/Application\ Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/213.7172.25.2113.9123335/Android\ Studio.app/Contents/jre/Contents/Home
    export PATH="$PATH:$JAVA_HOME/bin";
    echo "JAVA_HOME:" $JAVA_HOME
    echo "java -version:"
    java -version
  elif [ $1 = "1.8" ]; then
    export JAVA_HOME=/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
    export PATH="$PATH:$JAVA_HOME/bin";
    echo "JAVA_HOME:" $JAVA_HOME
    echo "java -version:"
    java -version
  fi
}

Now if I enter changeJava 11 or changeJava 1.8 in my terminal, I can change java for use general in MacOS