While do case and getopts shell script linux example

While do case and getopts shell script linux example

1. ‘ getopts ‘ is a syntax to get parse command line argument to our script , this also as an option of argument.

2. parse an argument -a, -b to the script.

while getopts “:ab” opt; do
case ${opt} in
a )
option_a=${OPTARG}
echo ” You choose : $option_a”
;;
b )
option_b=${OPTARG}
echo ” You choose : $option_b”
;;
\? ) echo “Usage: cmd [-a] [-b]”
;;
esac
done

How to Use Function in the shell script + logging using ‘ tee ‘ ?

1. Function in shell script .
– declare the function :
funct_name(){
echo ” fndong ”
}

– called the function ‘ funct_name() ‘
echo ” Hello” funct_name
2. simple program called function + logging using ‘ tee ‘.

2.1. Directory structures
– <My_Directory> , your main directory in linux environment.
– <My_Directory>/config/
config.properties
mysite=fndong.wordpress.com
-<My_Directory>/logs/
log.txt

– <My_Directory>/setToTheLogs.sh

2.2. Source Bash shell script ‘ setToTheLogs.sh ‘
– using tee command to write to ‘ log.txt ‘
– ‘ setLogMsg() ‘ is a function.
– call the function ‘ setLogMsg ‘

base_dir=/<My_Directory>/function_example
config_dir=${base_dir}/config
lOG_DIR=${base_dir}/logs

setLogMsg()
{
echo “\$1 : $1”
echo “\$2 : $2”
echo “$1 : $2 ” | tee -a $LOGFILE

}

# main line code
# use source command to read the parameter key in properties

if [ -f ${config_dir}/config.properties ];then
source ${config_dir}/config.properties
echo “test $mysite”
setLogMsg “INFO” $mysite
else
MSG_ERR=”There is no values in this properties ….”
setLogMsg ” ERROR ” ${MSG_ERR}
fi
3. ‘tee’ command – ‘ echo “$1 : $2 ” | tee -a $LOGFILE ‘ in the method ‘ setLogMsg() ‘ its inserted echo values into ‘ log.txt ‘

Selamat mencuba.