17 Jan 2013

KSH Tips

1. To include a file,

. ./error_handling.sh


2. To check whether a parameter is inputted or not,

if [[ -z $1 ]];then
  echo "Usage: `basename $0` arg1"
  echo "Please provide date in YYYYMMDD as the first parameter when running this script."
  return 100
fi



3. To convert a variable value to upper case,

YOUR_NAME="Mickey Mouse"
typeset -u $YOUR_NAME
echo $YOUR_NAME


The output is:

MICKEY MOUSE


4. To replace words in a file,

sed -e 's/&/&/g' "from.txt" > "to.txt"


5. To trap an error,

JOB_LOG_FILE=example.log
trap 'RC=$?; echo `date` "Error Line No.: $LINENO (Error Code: $RC)" >> $JOB_LOG_FILE' ERR



6. To output the current time in specific format,

echo `date +%y/%m/%d` `date +%H:%M:%S` "Hello World!"

The output is:

Thu Jan 17 16:31:07 HKT 2013 Hello World!


7. To check whether a word appears in a file,

JOB_LOG_FILE=example.log
info=`grep -Ei "error" $JOB_LOG_FILE | wc -l`
if [[ $ftp_info -qt 0 ]];then
  echo "Error(s) found."
else
  echo "No Error found."
fi



8. To execute a Java Jar file,

JOB_LOG_FILE=example.log
JAR_PATH=/home/scott
JAVA_NAMR=example.jar
PARAM_VALUE=test
echo `date` `java -jar $JAR_PATH/$JAR_NAME $PARAM_VALUE` >> $JOB_LOG_FILE



8. To housekeep files, e.g. for 30 days,

KEEP_FILES_IN_DAYS=30
find $LOG_PATH -name "job_*.log" -mtime +${KEEP_FILES_IN_DAYS} -exec rm -f {} \;



No comments: