if loop within for loop in shell script not working - bash

I have the following shell script in place to send out an email alert. When I only have the for loop everything works fine but when I try to add the if condition it does not seem to work and returns a null message body everytime. A snippet from the script is as below:
for host in $servers
do
connections=`ssh $host "netstat -a | grep ES | wc -l"`
echo "$connections" >> debug.log
echo "$host" >> debug.log
if [$connections -gt 0]
then
echo "------------------------------------------------------------------" >> $emailmessage
echo "Host: $host needs to be checked" >> $emailmessage
echo "------------------------------------------------------------------" >> $emailmessage
echo "$connections" >> $emailmessage
else
echo "Everything is fine"
fi
done
I always end up getting the line 21: [49: command not found error when i try to execute the script. I tried debugging but I figured out my script is not even getting inside the if loop.
Can someone please let me know what am I missing?
Thanks in advance.
/rd

There should be space around [ and ] also its better to put variable in quotes, so update your line as
...
if [ "$connections" -gt 0 ] ;
then
...

Related

Shell Script For Loop Exits After Finishing First Loop

Code works fine until the last for loop.
It tries to login database. Either, it establish a successful connection with database or not, script gives output OK/NOT OK depending to the connection and then exit the shell script. What should I do to solve this?
#!/bin/bash
read -p 'Username: ' var_username
read -sp 'Password: ' var_password
filename="$1"
while read -r line; do
name=$(sed 's/#.*$//g; s/(.*$//g; s/=.*$//g; s/).*$//g')
done < "$filename"
#retval=$? | tail -n1|grep OK
for tns in $name
do
tnsping $tns
if [ $? -eq 1 ]; then
echo $tns 'tnsping i calismiyor' >>tnslatest.log
else
echo $tns 'tnsping i calisiyor' >>tnslatest.log
working_tns+=($tns)
fi
done
#The following lines do not work properly.#
for working in $working_tns
do
echo "exit" | sqlplus -L $var_username/$var_password#$working | grep
Connected > /dev/null
if [ $? -eq 0 ]
then
echo "OK"
else
echo "NOT OK"
fi
done
For example; my tnsnames.ora file contains 4 tns.
So, I want to have for output like OK or NOT OK in total.
Thanks in advance.

Bash Logic Check - Repeating While Loop with nested "IF Then" statements

I'm writing a script to monitor my sip trunk and attempt to fix it. If it fails to fix the issue 6 times, then reboot the server. The script is called by cron via #reboot. I first had nested While Loops but that didn't work correctly so I switched to a never ending While Loop with two nested If Loops to perform the functions of the script.
I was wondering if somebody could take a quick look and see if the way I am attacking it makes sense and is logical approach.
Thank You,
Script as it stands:
#!/bin/bash
pwd="/srv/scripts"
count=0
echo "Script Started on $(date -u) Failure.Count=$count" >> "$pwd/failures.count"
start=start
while [ $start = "start" ]; do
sleep 420
var="$(asterisk -rx "pjsip show registrations" | grep -o Registered)"
if [ "$var" != "Registered" ]; then
amportal restart
count=$(( $count + 1 ))
echo "Trunk Failure on $(date -u) Failure.Count=$count" >> "$pwd/failures.count"
fi
if [ "$count" -gt 5 ]; then
echo "Server Reboot due to Failure.Count=$count on $(date -u)" >> "$pwd/reboot.notification"
reboot
fi
done
There is no need to use a variable in the while loop, or to capture the grep output into a variable.
#!/bin/bash
pwd="/srv/scripts"
count=0
echo "Script Started on $(date -u) Failure.Count=$count" >> "$pwd/failures.count"
# No need for a variable here
while true; do
# Fix indentation
sleep 420
# Again, no need for a variable; use grep -q
if ! asterisk -rx "pjsip show registrations" | grep -q Registered
then
amportal restart
count=$(( $count + 1 ))
echo "Trunk Failure on $(date -u) Failure.Count=$count" >> "$pwd/failures.count"
fi
if [ "$count" -gt 5 ]; then
echo "Server Reboot due to Failure.Count=$count on $(date -u)" >> "$pwd/reboot.notification"
reboot
fi
done
I would perhaps also collect all the log notices in a single log file, and use a more traditional log format with a time stamp and the script's name bofore each message.
Should the counter reset to zero if you see a success? Having the server reboot because you disconnected the network cable at the wrong time seems like something you'd want to avoid.

Checking ebay for registered emails shell

I am actually a beginner shell script developer, and i was given a script to work on, but i have not been able to successfully fix it, even after several days of studying. I want the script below to actually check a site and tell me which emails are already registered on the from the list of emails i will parse to it, and also save this emails.
The main challenge is that the code doesn't run at all, but i have a feeling i am close to making it work, and the fact that i always get the error "/bin/bash^M: bad interpreter: No such file or directory" when i try to run the code just sucks. I need help. Thanks
Below is the code i have at the moment.
#!bin/bash
#ebay.sh
CheckBay(){
wget -q "https://reg.bay.com/reg/ajax?
email=${em}&countryId=1&mode=5&eId=email" -O tmp/ganteng.txt
cat tmp/ganteng.txt | grep "Your email address is already registered
with eBay" > /dev/null;cekh=$?
if [ $cekh -eq 0 ];then
echo -e "[+] $em = \033[1m\e[1;32m[Valid in ebay]\E[0m"
echo -e "[+] $em = \033[1m\e[1;32m[Valid in ebay]\E[0m" >> log.txt
echo "$em" >> validebay.txt
else
echo -e "[+] $em = \033[1m\e[1;31m[Not Valid in ebay]\E[0m"
echo -e "[+] $em = \033[1m\e[1;31m[Not Valid in ebay]\E[0m" >> log.txt
echo "$em" >> notvalidebay.txt
fi
rm -f tmp/*
}
run(){
for em in `cat $email`
do
CheckBay $em
done
}
detail(){
if [ ! -d tmp ];then
mkdir tmp
fi
if [ ! -f $list ];then
echo "[?] file $email Not Found [!]"
exit
fi
}
read -p "[+] Enter list email = " email
detail
run
N/B: This is learning please, and i really need to be better

SHELL general function for action state

How to make a code bellow as a general function to be used entire script in bash:
if [[ $? = 0 ]]; then
echo "success " >> $log
else echo "failed" >> $log
fi
You might write a wrapper for command execution:
function exec_cmd {
$#
if [[ $? = 0 ]]; then
echo "success " >> $log
else
echo "failed" >> $log
fi
}
And then execute commands in your script using the function:
exec_cmd command1 arg1 arg2 ...
exec_cmd command2 arg1 arg2 ...
...
If you don't want to wrap the original calls you could use an explicit call, like the following
function check_success {
if [[ $? = 0 ]]; then
echo "success " >> $log
else echo "failed" >> $log
fi
}
ls && check_success
ls non-existant
check_success
There's no really clean way to do that. This is clean and might be good enough?
PS4='($?)[$LINENO]'
exec 2>>"$log"
That will show every command run in the log, and each entry will start with the exit code of the previous command...
You could put this in .bashrc and call it whenever
function log_status { [ $? == 0 ] && echo success>>/tmp/status || echo fail>>/tmp/status }
If you want it after every command you could make the prompt write to the log (note the original PS1 value is appended).
export PS1="\$([ \$? == 0 ] && echo success>>/tmp/status || echo fail>>/tmp/status)$PS1"
(I'm not experienced with this, perhaps PROMPT_COMMAND is a more appropriate place to put it)
Or even get more fancy and see the result with colours.
I guess you could also play with getting the last executed command:
How do I get "previous executed command" in a bash script?
Get name of last run program in Bash
BASH: echoing the last command run

Error with shell scripting

!#/bin/bash
svnadmin dump /path/to/repo | gzip -9 > /path/to/backup.bak-$(date +"%d\%m\%Y--%T").dump.gz
if ( `echo $?` -eq 0)
then
echo "hello world" | mail -s "a subject" someone#wherever.com
else
echo "sorry, no way out" | mail -s "a subject" someone#wherever.com
exit 1
fi
there is an edit with the question
Any help is appreciated. Thanks
The output i get is the else part " sorry no way out! but what i expect to get is a hello world as the dump command works perfectly
Your IF clause should be: if [ $? -eq 0 ]. Notice the square brackets and the whitespaces around them.
Here is how I solved it:
!#/bin/bash
ls;
if [ $? -eq 0 ]
Your shebang is wrong. It should be #!. Also,
do not bother explicitly checking $?. Just do:
if ls; then
...
else
...
fi

Resources