Oracle Database Alert log script error - linux

i wrote alert log script and some how this is not working and not throwing any error when i execute the script
i am suspecting sed part is not working properly. could you please advice where i am doing wrong?
here is the piece of code
#!/bin/sh
## Heading #########################################################################################
#---------------------------------------------------------------------------------------#
# script usage #
#---------------------------------------------------------------------------------------#
_usage() {
echo "Usage: $0 ORACLE_SID "
} # _usage
ORACLE_SID="$1"
setenv ()
{
eval "$1=$2"
export "$1"
} # setenv
unsetenv ()
{
while [ $# -gt 0 ]
do
unset "$1"
shift
done
} # unsetenv
if [ $# -ne 1 ]; then
_usage
exit 1
fi
Env=/u01/app/oracle/config
HN=`uname -n`
ERROR_FILE=/tmp/${ORACLE_SID}_error.log
HN=`hostname`
DBA_MAIL="oracle.mail#company"
DBA_PAGE=""
#+--------------------------------------------------------------------------------------+
#| get oracle environment variables from our common env dir |
#+--------------------------------------------------------------------------------------+
if [ -r $Env/${ORACLE_SID}.env ]
then
. $Env/${ORACLE_SID}.env
else
ORACLE_SID=""
fi
#+--------------------------------------------------------------------------------------+
#| just checking for Oracle Env variables for connecting database |
#+--------------------------------------------------------------------------------------+
if [ "$ORACLE_SID" = "" ]
then
echo "ORACLE_SID is invalid"
exit 1
fi
if [ "$ORACLE_HOME" = "" ]
then
echo "The environment variable ORACLE_HOME must be set"
exit 1
fi
if [ "$ORACLE_BASE" = "" ]
then
echo "The environment variable ORACLE_BASE must be set"
exit 1
fi
_AlertLogLoc ()
{
ALERTLOG=`$ORACLE_HOME/bin/sqlplus -s "/as sysdba" << EOF
set head off pause off term on feed off timing off
select value from v\\$parameter where name like 'background_dump_dest';
exit;
EOF`
}
_AlertLogLoc
echo $ALERTLOG
export ALERTLOG
if [ -f $ALERTLOG/alert_${ORACLE_SID}.log ]; then
echo "Found Database Alert log"
else
echo "Alert log not found .. exit from script"
fi
if [ -f $ALERTLOG/alert_${ORACLE_SID}.skip ]; then
echo " ORACLE_SID skip error file found"
SKIP_ERR=`cat $ALERTLOG/alert_$ORACLE_SID.skip|xargs|sed -e 's/ /|/g'`
echo $SKIP_ERR
else
echo "No errors will be excluded"
fi
REC_CUR_ALSIZE=/oraworkspace/OSE/logs/alert_${ORACLE_SID}.size # file to record current alert log lines
#---------------------------------------------------------------------------------------------------------#
# let Capture ORA- error from the alert log #
#---------------------------------------------------------------------------------------------------------#
if [ -f $REC_CUR_ALSIZE ]; then
ALSIZE=`cat $REC_CUR_ALSIZE|sed -e 's/^[ \t]*//'`
ALSIZE=`expr $ALSIZE + 1`
else
ALSIZE=0
fi
if [ $ALSIZE -eq 0 ]; then
echo "PROBABLY RUNNUNG THE SCRIPT FIRST TIME"
sed -n $ALSIZE',$p' $ALERTLOG/alert_${ORACLE_SID}.log |egrep -v "$SKIP_ERR"|grep -i 'ORA-' > /tmp/${ORACLE_SID}_error.log
#`wc -l $ALERTLOG/alert_${ORACLE_SID}.log > $REC_CUR_ALSIZE
cat $ALERTLOG/alert_${ORACLE_SID}.log|wc -l > /oraworkspace/OSE/logs/alert_${ORACLE_SID}.size
#ALSIZE=`cat $ALERTLOG/alert_${ORACLE_SID}.log |wc -l`
else
sed -n ${ALSIZE}',$p' $ALERTLOG/alert_${ORACLE_SID}.log |egrep -v "$SKIP_ERR"|grep -i 'ORA-' > /tmp/${ORACLE_SID}_error.log
#wc -l $ALERTLOG/alert_${ORACLE_SID}.log >> $REC_CUR_ALSIZE
cat $ALERTLOG/alert_${ORACLE_SID}.log |wc -l > /oraworkspace/OSE/logs/alert_${ORACLE_SID}.size
fi
#---------------------------------------------------------------------------------------------------------#
# Notify if any errors are found #
#---------------------------------------------------------------------------------------------------------#
ERR_CNT=`cat /tmp/${ORACLE_SID}_error.log |wc -l`
if [ $ERR_CNT -ne 0 ]; then
echo "Errors found in the alert log. send email notification"
mailx -s "${HN}:${ORACLE_SID} ORA error Found in the alert log" ${DBA_MAIL} < $ERROR_FILE
#mailx -s "${HN}:${ORACLE_SID} ORA error Found in the alert log" ${DBA_MAIL} < $ERROR_FILE
else
echo " No errors found in the alert log"
fi

If $ALERTLOG/alert_$ORACLE_SID.skip doesn't exist or is empty (around line 94), the egrep -v "$SKIP_ERR" will exclude all lines from the sed output, so it will not have a chance to see any remaining ORA- errors.
ALSIZE=1
SKIP_ERR=""
sed -n $ALSIZE',$p' $ALERTLOG/alert_${ORACLE_SID}.log |\
egrep -v "$SKIP_ERR"|wc -l
0
SKIP_ERR="dummy"
sed -n $ALSIZE',$p' $ALERTLOG/alert_${ORACLE_SID}.log |\
egrep -v "$SKIP_ERR"|wc -l
15165
So you need to set your SKIP_ERR to something when it's not set or empty (if your skip file is empty). You haven't said if that is the case or shown the script output, but it seems to work apart from that.
Also not that if ALSIZE is zero sed isn't happy, at least in RHEL 5:
ALSIZE=0
SKIP_ERR="dummy"
sed -n $ALSIZE',$p' $ALERTLOG/alert_${ORACLE_SID}.log |\
egrep -v "$SKIP_ERR"|wc -l
sed: -e expression #1, char 4: invalid usage of line address 0
0
And when you test that the file exists at line 91, you show a message stating that and suggesting you'll stop there, but there is no exit after line 94; doesn't seem to be relevant here but seems like an oversight?

Related

Can't parse a string with brace expansion operations into a command

have some problem with shell script.
In our office we set up only few commands, that available for devs when they are trying ssh to server. It is configured with help of .ssh/authorized_keys file and available command for user there is bash script:
#!/bin/sh
if [[ $1 == "--help" ]]; then
cat <<"EOF"
This script has the purpose to let people remote execute certain commands without logging into the system.
For this they NEED to have a homedir on this system and uploaded their RSA public key to .ssh/authorized_keys (via ssh-copy-id)
Then you can alter that file and add some commands in front of their key eg :
command="/usr/bin/dev.sh",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty
The user will do the following : ssh testuser#server tail testserver.example.com/2017/01/01/user.log
EOF
exit 0;
fi
# set global variable
set $SSH_ORIGINAL_COMMAND
# set the syslog path where the files can be found
PATH="/opt/syslog/logs"
# strip ; or any other unwanted signs out of the command, this prevents them from breaking out of the setup command
if [[ $1 != "" ]]; then
COMMAND=$1
COMMAND=${COMMAND//[;\`]/}
fi
if [[ $2 != "" ]]; then
ARGU1=$2
ARGU1=${ARGU1//[;\`]/}
fi
if [[ $3 != "" ]]; then
ARGU2=$3
ARGU2=${ARGU2//[;\`]/}
fi
if [[ $4 != "" ]]; then
ARGU3=$4
ARGU3=${ARGU3//[;\`]/}
fi
# checking for the commands
case "$COMMAND" in
less)
ARGU2=${ARGU1//\.\./}
FILE=$PATH/$ARGU1
if [ ! -f $FILE ]; then
echo "File doesn't exist"
exit 1;
fi
#echo " --------------------------------- LESS $FILE"
/usr/bin/less $FILE
;;
grep)
if [[ $ARGU2 == "" ]]; then
echo "Pls give a filename"
exit 1
fi
if [[ $ARGU1 == "" ]]; then
echo "Pls give a string to search for"
exit 1
fi
ARGU2=${ARGU2//\.\./}
FILE=$PATH/$ARGU2
/usr/bin/logger -t restricted-command -- "------- $USER Executing grep $ARGU1 \"$ARGU2\" $FILE"
if [ ! -f $FILE ]; then
echo "File doesn't exist"
/usr/bin/logger -t restricted-command -- "$USER Executing $#"
exit 1;
fi
/bin/grep $ARGU1 $FILE
;;
tail)
if [[ $ARGU1 == "" ]]; then
echo "Pls give a filename"
exit 1
fi
ARGU1=${ARGU1//\.\./}
FILE=$PATH/$ARGU1
if [ ! -f $FILE ]; then
echo "File doesn't exist"
/usr/bin/logger -t restricted-command -- "$USER Executing $# ($FILE)"
exit 1;
fi
/usr/bin/tail -f $FILE
;;
cat)
ARGU2=${ARGU1//\.\./}
FILE=$PATH/$ARGU1
if [ ! -f $FILE ]; then
echo "File doesn't exist"
exit 1;
fi
/bin/cat $FILE
;;
help)
/bin/cat <<"EOF"
# less LOGNAME (eg less testserver.example.com/YYYY/MM/DD/logfile.log)
# grep [ARGUMENT] LOGNAME
# tail LOGNAME (eg tail testserver.example.com/YYYY/MM/DD/logfile.log)
# cat LOGNAME (eg cat testserver.example.com/YYYY/MM/DD/logfile.log)
In total the command looks like this : ssh user#testserver.example.com COMMAND [ARGUMENT] LOGFILE
EOF
/usr/bin/logger -t restricted-command -- "$USER HELP requested $#"
exit 1
;;
*)
/usr/bin/logger -s -t restricted-command -- "$USER Invalid command $#"
exit 1
;;
esac
/usr/bin/logger -t restricted-command -- "$USER Executing $#"
The problem is next:
when i try to exec some command, it takes only first argument, if i do recursion in files by using {n,n1,n2} - it doesn't work:
[testuser#local ~]$ ssh testuser#syslog.server less srv1838.example.com/2017/02/10/local1.log |grep 'srv2010' | wc -l
0
[testuser#local ~]$ ssh testuser#syslog.server less srv2010.example.com/2017/02/10/local1.log |grep 'srv2010' | wc -l
11591
[testuser#local ~]$ ssh testuser#syslog.server less srv{1838,2010}.example.com/2017/02/10/local1.log |grep 'srv2010' | wc -l
0
[testuser#local ~]$ ssh testuser#syslog.server less srv{2010,1838}.example.com/2017/02/21/local1.log |grep 'srv2010' | wc -l
11591
Could someone help me, how can i parse\count command arguments to make it work?
Thank you and have a nice day!
The number of arguments for a bash script would be $#. As a quick example:
#!/bin/bash
narg=$#
typeset -i i
i=1
while [ $i -le $narg ] ; do
echo " $# $i: $1"
shift
i=$i+1
done
gives, for bash tst.sh a b {c,d}
4 1: a
3 2: b
2 3: c
1 4: d
In your script, the command to execute (cat, less, ...) gets explicitly only the second argument to the script. If you want to read all arguments, you should do something like this (note: only a hint, removed all sorts of checks etc..)
command="$1"
shift
case $command in
(grep) pattern="$1"
shift
while [ $# -gt 0 ] ; do
grep "$pattern" "$1"
shift
done
;;
esac
note: added some quotes as comment suggested, but, being only a hint, you should carefully look at quoting and your checks in your own script.
Less command working now:
case "$COMMAND" in
less)
if [[ $ARGU1 == "" ]]; then
echo "Pls give a filename"
exit 1
fi
FILES_LIST=${#:2}
FILE=(${FILES_LIST//\.\./})
for v in "${FILE[#]}";do
v=${v//[;\']/}
if [ ! -f $v ]; then
echo "File doesn't exist"
fi
/usr/bin/less $PATH/$v
done;;
tail command works too with 2 and more files, but i can't execute tail -f command on two files unfortunately.

updating a file using tee randomly fails in linux bash script

when using sed -e to update some parameters of a config file and pipe it to | tee (to write the updated content into the file), this randomly breaks and causes the file to be invalid (size 0).
In Summary, this code is used for updating parameters:
# based on the provided linenumber, add some comments, add the new value, delete old line
sed -e "$lineNr a # comments" -e "$lineNr a $newValue" -e "$lineNr d" $myFile | sudo tee $myFile
I set up an script which calls this update command 100 times.
In a Ubuntu VM (Parallels Desktop) on a shared Directory with OSX this
behaviour occurs up to 50 times
In a Ubuntu VM (Parallels Desktop) on the
Ubuntu partition this behaviour occurs up to 40 times
On a native System (IntelNUC with Ubuntu) this behaviour occurs up to 15 times
Can someone explain why this is happening?
Here is a fully functional script where you can run the experiment as well. (All necessary files are generated by the script, so you can simply copy/paste it into a bashscriptfile and run it)
#!/bin/bash
# main function at bottom
#====================
#===HELPER METHOD====
#====================
# This method updates parameters with a new value. The replacement is performed linewise.
doUpdateParameterInFile()
{
local valueOfInterest="$1"
local newValue="$2"
local filePath="$3"
# stores all matching linenumbers
local listOfLines=""
# stores the linenumber which is going to be replaced
local lineToReplace=""
# find value of interest in all non-commented lines and store related lineNumber
lineToReplace=$( grep -nr "^[^#]*$valueOfInterest" $filePath | sed -n 's/^\([0-9]*\)[:].*/\1/p' )
# Update parameters
# replace the matching line with the desired value
oldValue=$( sed -n "$lineToReplace p" $filePath )
sed -e "$lineToReplace a # $(date '+%Y-%m-%d %H:%M:%S'): replaced: $oldValue with: $newValue" -e "$lineToReplace a $newValue" -e "$lineToReplace d" $filePath | sudo tee $filePath >/dev/null
# Sanity check to make sure file did not get corrupted by updating parameters
if [[ ! -s $filePath ]] ; then
echo "[ERROR]: While updating file it turned invalid."
return 31
fi
}
#===============================
#=== Actual Update Function ====
#===============================
main_script()
{
echo -n "Update Parameter1 ..."
doUpdateParameterInFile "Parameter1" "Parameter1 YES" "config.txt"
if [[ "$?" == "0" ]] ; then echo "[ OK ]" ; else echo "[FAIL]"; return 33 ; fi
echo -n "Update Parameter2 ..."
doUpdateParameterInFile "Parameter2" "Parameter2=90" "config.txt"
if [[ "$?" == "0" ]] ; then echo "[ OK ]" ; else echo "[FAIL]"; return 34 ; fi
echo -n "Update Parameter3 ..."
doUpdateParameterInFile "Parameter3" "Parameter3 YES" "config.txt"
if [[ "$?" == "0" ]] ; then echo "[ OK ]" ; else echo "[FAIL]"; return 35 ; fi
}
#=================
#=== Main Loop ===
#=================
#generate file config.txt
printf "# Configfile with 3 Parameters\n#[Parameter1]\n#only takes YES or NO\nParameter1 NO \n\n#[Parameter2]\n#Parameter2 takes numbers\nParameter2 = 100 \n\n#[Parameter3]\n#Parameter3 takes YES or NO \nParameter3 YES\n" > config.txt
cp config.txt config.txt.bkup
# Start the experiment and let it run 100 times
cnt=0
failSum=0
while [[ $cnt != "100" ]] ; do
echo "==========run: $cnt; fails: $failSum======="
main_script
if [[ $? != "0" ]] ; then cp config.txt.bkup config.txt ; failSum=$(($failSum+1)) ; fi
cnt=$((cnt+1))
sleep 0.5
done
regards
DonPromillo
The problem is that you're using tee to overwrite $filepath at the same time as sed is trying to read from it. If tee truncates it first then sed gets an empty file and you end up with a 0 length file at the other end.
If you have GNU sed you can use the -i flag to have sed modify the file in place (other versions support -i but require an argument to it). If your sed doesn't support it you can have it write to a temp file and move it back to the original name like
tmpname=$(mktemp)
sed -e "$lineToReplace a # $(date '+%Y-%m-%d %H:%M:%S'): replaced: $oldValue with: $newValue" -e "$lineToReplace a $newValue" -e "$lineToReplace d" "$filePath" > "$tmpname"
sudo mv "$tmpname" "$filePath"
or if you want to preserve the original permissions you could do
sudo sh -c "cat '$tmpname' > '$filePath'"
rm "$tmpname"
or use your tee approach like
sudo tee "$filePath" >/dev/null <"$tmpname"
rm "$tmpname"

Bash scripts errors

I'm trying to run those scripts but I keep receiving errors messages:
1-
#!/bin/bash
filename=$1
if [ -f $filename ]
then
owner=`stat -c %U $filename`
grep $owner /etc/passwd
if [ $? -eq 0 ]; then
perm=`stat -c %a $filename | head -c 1`
if [ $perm -gt 3 ]; then
cat $filename | grep NOTE
fi
fi
fi
the error message is :
stat: missing operand Try `stat --help' for more information.
2-
#!/bin/bash
NoSum=$1
sum=0
echo "Please enter $NoSum values one at a time"
for (( i=1; i<=$NoSum; i++ ))
do
echo "Next Value?"
read num
let "a = $sum + $num"
sum=$a
done
echo "The sum is : $sum"
the error message is:
Please enter values one at a time ./scr3: line 6: ((: i<=: syntax
error: operand expected (error token is "<=") The sum is : 0
3-
#!/bin/bash
dir=$1
if [ -d $dir ]
then
perm=`stat -c %a $dir | head -c 1`
if [ $perm -gt 5 ]; then
cd $dir
for file in $dir/*
do
if ! [ -x "$file" ]
then
echo "$file"
fi
done
fi
fi
the error message is:
stat: missing operand Try `stat --help' for more information. ./scr4:
line 8: [: -gt: unary operator expected
any idea how to fix them ?
Nothing is wrong about the programs.You are not supplying the command line arguments.You must run it as
1 and 3:
./script.sh <filename>
2:
./script.sh <number>
$1 stands for the first command line argument
You need to quote variables in bash to prevent word-splitting issues, both in test brackets [] and most of the time in other use.
So your first script would be
#!/bin/bash
filename="$1"
if [ -f "$filename" ]
then
owner="`stat -c %U "$filename"`"
grep "$owner" /etc/passwd
if [ $? -eq 0 ]; then
perm="`stat -c %a "$filename" | head -c 1`"
if [ "$perm" -gt 3 ]; then
cat "$filename" | grep NOTE
fi
fi
fi
The others have similar erros

check file or user script assignment problems

Below is the assignment for the bash shell script I'm writing. I'm having a
problem with -u information being output even though I am using the -f option.
This class is a beginner class, so please bear with me. Would be grateful to
have some input on my code. Thanks for taking the time to check this out if you
do.
Here is the sample output:
[***#***]$ chk3 -f share
share is a directory and it is readable | writable | executable | abecker is
currently logged in their home directory is /students/abecker
Here is the usage
chk -f filepath
If filepath exists, output in readable sentences
if it is a symbolic link, say so. You do not have to continue and report the
permissions.
if it doesn't exist, say so. Don't continue to report the permissions
report what it is: file, directory, or something else, and continue to
report the permissions:
report what combination of read, write and execute access rights your
program has for the data. Note that this is dependent on who runs your
program. Do not attempt to do this by looking at the permissions as output
by ls -l. You must use the test operators to do this.
If filepath does not exist (and is not a symbolic link), your program should
report this instead in an informative error message. In this case, you
should exit with an error.
chk -u user
If the user exists on the system, report
the path to the user's home directory
if the user is currently logged in, say so. Otherwise, report when they last
logged in. (Take some care so that this is generated reliably and quickly.)
If the user doesn't exist, report this in an informative error message, and
exit with an error.
Here is my code
#!/bin/bash
if [ $# -gt 2 ]
then
echo "only 2 aruments can be used"
exit 1
fi
if [ "$1" != '-f' -a "$1" != '-u' ]
then
echo "first argument must be -f or -u"
exit 1
fi
if [ "$1" = '-f' -a $# -ne 2 ]
then
echo 'Usage: chk -f [FILEPATH]'
exit 1
fi
if [ "$1" = '-f' ]
then
FILEPATH=$2
fi
if [ -L "$FILEPATH" ]
then
echo "$FILEPATH is a symbolic link"
exit 0
elif [ -d "$FILEPATH" ]
then
echo -e "$(basename "$FILEPATH") is a directory and it is \c"
elif [ -f "$FILEPATH" ]
then
echo -e "$(basename "$FILEPATH") is a file and it is \c"
else
echo "I cannot determine what $(basename "$FILEPATH") is"
exit 1
fi
if [ -r "$FILEPATH" ]
then
echo -e "readable | \c"
fi
if [ -w "$FILEPATH" ]
then
echo -e "writable | \c"
fi
if [ -x "$FILEPATH" ]
then
echo -e "executable | \c"
fi
if [ "$1" = '-u' -a $# -eq 1 ]
then
USER=$LOGNAME
elif [ "$1" = '-u' -a $# -eq 2 ]
then
USER=$2
fi
USERINFO=$(grep "^$USER:" /etc/passwd)
if ! grep "^$USER:" /etc/passwd > /dev/null
then
echo "$USER cannot be found on this system"
exit 1
fi
if ! who | grep "^$USER " > /dev/null
then
echo "$USER is not currently logged on and last logged on"
echo "$(last -1 "$USER")"
exit 0
else
echo "$USER is currently logged in their home directory is"
echo "$(echo "$USERINFO" | awk -F":" '{print $6}')"
fi
You're not putting the processing of different options into different blocks; the code simply passes through everything for all options.
e.g. for the -f option, you have:
if [ "$1" = '-f' ]
then
FILEPATH=$2
fi
and then process all the options for filepath, without putting them into the if statement, so if you pass in either -f or -u, it always passes into the code:
if [ -L "$FILEPATH" ]
then
echo "$FILEPATH is a symbolic link"
exit 0
elif
If you don't want to break your program into functions, what you want to do is put all the code relating to processing the -f option into the same if-statement, somewhat like:
if [ "$1" = '-f' ]
then
FILEPATH=$2
if [ -L "$FILEPATH" ]
then
echo "$FILEPATH is a symbolic link"
exit 0
elif [ -d "$FILEPATH" ]
then
echo -e "$(basename "$FILEPATH") is a directory and it is \c"
elif [ -f "$FILEPATH" ]
then
echo -e "$(basename "$FILEPATH") is a file and it is \c"
else
echo "I cannot determine what $(basename "$FILEPATH") is"
exit 1
fi
if [ -r "$FILEPATH" ]
then
echo -e "readable | \c"
fi
if [ -w "$FILEPATH" ]
then
echo -e "writable | \c"
fi
if [ -x "$FILEPATH" ]
then
echo -e "executable | \c"
fi
fi # if [ "$1" = '-f' ]
Similarly for the -u option, you need to break it into multiple statements and then process all the options for the statement:
if [ "$1" = 'u' ]
then
if [ $# -eq 1 ]
then
USER=$LOGNAME
elif [ $# -eq 2 ]
then
USER=$2
fi
USERINFO=$(grep "^$USER:" /etc/passwd)
if ! grep "^$USER:" /etc/passwd > /dev/null
then
echo "$USER cannot be found on this system"
exit 1
fi
if ! who | grep "^$USER " > /dev/null
then
echo "$USER is not currently logged on and last logged on"
echo "$(last -1 "$USER")"
exit 0
else
echo "$USER is currently logged in their home directory is"
echo "$(echo "$USERINFO" | awk -F":" '{print $6}')"
fi
fi # if [ "$1" = '-u' ]
I would, however recommend putting the code that acts on the options into shell functions, which makes it much easier to read the code; e.g.
filepath() {
FILEPATH="$1"
if [ -L "$FILEPATH" ]
then
echo "$FILEPATH is a symbolic link"
exit 0
elif [ -d "$FILEPATH" ]
then
echo -e "$(basename "$FILEPATH") is a directory and it is \c"
elif [ -f "$FILEPATH" ]
then
echo -e "$(basename "$FILEPATH") is a file and it is \c"
else
echo "I cannot determine what $(basename "$FILEPATH") is"
exit 1
fi
if [ -r "$FILEPATH" ]
then
echo -e "readable | \c"
fi
if [ -w "$FILEPATH" ]
then
echo -e "writable | \c"
fi
if [ -x "$FILEPATH" ]
then
echo -e "executable | \c"
fi
}
And then for the processing code:
if [ "$1" = '-f' ]
then
filepath "$2"
fi
and something similar for the -u option.

Linux Script Nested if-statements giving syntax error

I am trying to nest multiple if-statements as the following:
#!/bin/bash
# start_server.sh
#
# Use this script to start the MarketDataTransmitter.
#
# Usage: ./start_server.sh Starts the MarketDataTransmitter.
reset=$(tput sgr0)
red=$(tput setaf 1)
green=$(tput setaf 2)
yellow=$(tput setaf 3)
cyan=$(tput setaf 6)
echo
directory=$(ls -l)
check_exist=$(awk -v a="$directory" -v b="MarketDataTransmitter" 'BEGIN { print index(a, b) }')
if [ "$check_exist" = "0" ]; then
# MarketDataTransmitter is not present.
echo "${red}[ERROR]${reset} Could not start ${yellow}MarketDataTransmitter${reset}."
echo " ${yellow}MarketDataTransmitter${reset} could not be found."
else
# MarketDataTransmitter is present.
processes=$(ps -ef | grep -i "MarketDataTransmitter" | grep -v "grep" | grep -v "bash" | awk '{ print $8 }')
check_run=$(awk -v a="$processes" -v b="MarketDataTransmitter" 'BEGIN { print index(a, b) }')
if [ "$check_run" = "0" ]; then
# MarketDataTransmitter is not running.
if [ -e "srv.log" ]; then
if [ -s "srv.log" ]; then
if [ -d "logs" ]; then
date_time=$(date '+%Y%m%d_%H_%M_%S')
new_log_name="srv_$date_time.log"
mv srv.log $new_log_name
mv $new_log_name logs
else
mkdir logs
date_time=$(date '+%Y%m%d_%H_%M_%S')
new_log_name="srv_$date_time.log"
mv srv.log $new_log_name
mv $new_log_name logs
fi
else
echo "srv.log is empty and will be removed."
rm -rf srv.log
fi
else
# No srv.log but this is to start MarketDataTransmitter so we can ignore.
fi
./MarketDataTransmitter > srv.log &
echo "${yellow}MarketDataTransmitter${reset} has been started."
else
# MarketDataTransmitter is already running.
echo "${red}[ERROR]${reset} Could not start ${yellow}MarketDataTransmitter${reset}."
echo " ${yellow}MarketDataTransmitter${reset} is already running."
fi
fi
echo
However it is giving me syntax complaints saying:
syntax error near unexpected token `fi'
on the very last 'fi'
Does anyone know why?
Thanks.
[EDIT] Full code has been posted.
You have an else statement and fi statement with nothing between them on lines 44-46 (just a comment between them). In bash, you need to have some statement in the body of that else block, or take the else block out.

Resources