Bash Script - Integer expression expected - bash

With the below code, I keeping getting:
line 9: [: 8.8.8.8: integer expression expected
Unsure Why?
#!/bin/bash
sourceFile="file.log"
targetFile="2file.log"
ping="8.8.8.8"
while IFS='' read -r line || [[ -n "$line" ]]; do
echo "$line" >> "$targetFile"
sudo service networking restart
ping -q -c 5 "$ping"
if [ "$ping" -ne 0 ]; then
sed -n -e 8p "$2file.log"
fi
done < "$sourceFile"

Because you are trying to compare "8.8.8.8" (string) to 0 (integer)
ping="8.8.8.8"
if [ "$ping" -ne 0 ]; then
ping variable is string.

You are comparing a string value ("8.8.8.8") to an integer value (0)
You can retrieve the exit code of your ping command with $?
ping="8.8.8.8"
ping -q -c 5 "$ping"
ping=$?
if [ $ping -ne 0 ]; then
echo "NOTOK"
else
echo "OK"
fi
Check this post

Related

Logical OR evaluates all expression in Bash script

Consider this simple shell script:
#!/bin/bash
exp1="[ $1 -gt 5 ]";
exp2="[ `ping localhost -c 4 | wc -l` -gt 0 ]";
if eval $exp1 || eval $exp2
then
echo Ok!
fi
I was expecting that passing 10 to this script, the ping was not executed, but it is clearly executed (since the script takes some seconds to write "Ok!").
I was wondering if there is a way to avoid/optimize this behavior?
It will execute ping because you have:
exp2="[ `ping localhost -c 4 | wc -l` -gt 0 ]";
which uses command substitution before evaluating the condition due to double quotes.
Use single quotes to delay the execution until the eval line, like so:
#!/bin/bash
exp1='[[ $1 -gt 5 ]]'
exp2='[[ $(ping localhost -c 4 | wc -l) -gt 0 ]]'
if eval $exp1 || eval $exp2
then
echo Ok!
fi
Better yet, use functions. Don't store commands in variables!
exp1() { [[ $1 -gt 5 ]]; }
exp2() { [[ $(ping localhost -c 4 | wc -l) -gt 0 ]]; }
if exp1 "$1" || exp2
then
echo Ok!
fi

Bash For Loop With If & Elif Logic Broken

I've been playing with bash scripting for 40'ish days with 0 experience so forgive me if my code looks like crap. I have a script that will take the configured NTP servers out of the /etc/ntp.conf file (/root/ntp.conf for testing)
NTPSRVCounter=1
echo "--- NTP Configuration ---"
echo " "
while read -r line; do
if [ $NTPSRVCounter == 1 ] ; then
echo "Primary NTP: $line"
SEDConfiguredNTP1="$(echo $line | sed 's/\./\\./g')"
((NTPSRVCounter++))
echo " "
else
SEDConfiguredNTP2="$(echo $line | sed 's/\./\\./g')"
echo "Secondary NTP: $line"
echo ""
fi
done < <(grep -o -P '(?<=server ).*(?= iburst)' /root/ntp.conf)
And asks you if you want to change it with a case statement:
echo "Do you wish to change it? [Y/n]"
NTPSRVCounter2=1
read opt
case $opt in
Y|y) read -p "Enter in your primary NTP server: " -e -i '0.debian.pool.ntp.org' UserInputNTP1
read -p "Enter in your secondary NTP serer: " -e -i '1.debian.pool.ntp.org' UserInputNTP2
for NTP in "$UserInputNTP1" "$UserInputNTP2" ; do
is_fqdn "$NTP"
if [[ $? == 0 && $NTPSRVCounter2 == 1 ]] ; then
SEDUserInput1=$(echo $UserInputNTP1 | sed 's/\./\\./g')
((NTPSRVCounter2++))
elif [[ $? == 0 && $NTPSRVCounter2 == 2 ]] ; then
SEDUserInput2=$(echo $UserInputNTP2 | sed 's/\./\\./g')
sudo sed -i "s/$SEDConfiguredNTP1/$SEDUserInput1/g" /root/ntp.conf
sudo sed -i "s/$SEDConfiguredNTP2/$SEDUserInput2/g" /root/ntp.conf
else
echo "Fail!!! :-( "
fi
done
;;
N|n) return 0
;;
*) echo "I don't know what happened, but, eh, you're not supposed to be here."
;;
esac
The problem is with the "elif" statement and the function "is_fqdn" on the second run of the function. If I put "bash -x" on the script and run it, I see "is_fqdn" returning 0 on both runs of the function, but the elif statement "$?" is coming up as 1 instead of 0.
The two functions used are below. Have to validate NTP addresses as either valid domain names or I.P. addresses, right? :)
is_fqdn() {
hostname=$1
if [[ "$hostname" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
valid_ip "$hostname"
elif [[ "$hostname" == *"."* && "$hostname" != "localhost." && "$hostname" != "localhost" ]] ; then
return 0
else
return 1
fi
host $hostname > /dev/null 2>&1 || return 1
}
valid_ip(){
local stat=1
local ip=$1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS="."
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return "$stat"
}
The condition in your if sets the value of $?, and that is what's used by the condition in the elif part, not the return value of is_fqdn. You need to save the value if you want to use it in multiple places:
is_fqdn "$NTP"
is_fqdn_rv=$?
if [[ $is_fqdn_rv == 0 && $NTPSRVCounter2 == 1 ]] ; then
SEDUserInput1=$(echo $UserInputNTP1 | sed 's/\./\\./g')
((NTPSRVCounter2++))
elif [[ $is_fqdn_rv == 0 && $NTPSRVCounter2 == 2 ]] ; then
SEDUserInput2=$(echo $UserInputNTP2 | sed 's/\./\\./g')
sudo sed -i "s/$SEDConfiguredNTP1/$SEDUserInput1/g" /root/ntp.conf
sudo sed -i "s/$SEDConfiguredNTP2/$SEDUserInput2/g" /root/ntp.conf
else
echo "Fail!!! :-( "
fi

Ping a host and output in CSV format in bash

I have a CSV file named ip.csv in the following format:
Host,Status
192.168.0.2
192.168.0.4
I want to ping IP and save output in the same file, ip.csv, next to the host. Output should look like:
Host,Status
192.168.0.2,Alive
192.168.0.4,Down
When I executed below script, I didn't get desired output:
#!/bin/bash
while IFS=',' read -r host status
do
ping -c 1 "$host"
if [ $? -eq 0 ]; then
echo -e "$host,Alive" >> ip.csv
else
echo -e "$host,Down" >> ip.csv
fi
done < ip.csv
Please suggest.
you can do it using this changes -
#!/bin/bash
a=""
while IFS=',' read -r host status
do
if [ "$host" = "Host" ]; then
a="${a}${host}"','"${status}"$'\n'
else
ping -c 1 "$host"
if [ $? -eq 0 ]; then
a="${a}${host}"',Alive'$'\n'
else
a="${a}${host}"',Down'$'\n'
fi
fi
done < ip.csv
echo -e "${a}" > ip.csv

Having difficulty writing a script to sort words

I am dealing with sorting words in Bash according to a given argument. I am given either argument -r, -a , -v or -h and according to it there are options to sort the words, as you can see at my "help".
Somehow, if I pass the argument -r it creates an error. I really don't understand what I am doing wrong, as if[["$arg"=="-a"]] works, but I have to use case somehow.
Here is my code:
#!/bin/bash
# Natalie Zubkova , zubkonat
# zubkonat#cvut.fel.cz , LS
#help
help="This script will calculate occurances of words in a given file, and it will sort them according to the given argument in following order> \n
without parametre = increasing order according to a number of occurance\n
-r = decreasing order according to a number of occurance\n
-a = in alphabetical increasing order\n
-a -r = in alphabetical decreasing order\n
There are also special cases of the given parametre, when the script is not sorting but:\n
-h = for obtaining help \n
-v = for obtaining a number of this task "
# this function will divide a given chain into a words, so we can start calculating the occurances, we also convert all the capital letters to the small ones by - tr
a=0;
r=0;
EXT=0;
if [ "$1" == "-h" ]; then
echo $help
exit 0
fi
if [ "$2" == "-h" ]; then
echo $help
exit 0
fi
if [ "$1" == "-v" ]; then
echo "5"
exit 0
fi
if [ "$2" == "-v" ]; then
echo "5"
exit 0
fi
function swap {
while read x y; do
echo "$y" "$x";
done
}
function clearAll {
sed -e 's/[^a-z]/\n/gI' | tr '[A-Z]' '[a-z]' | sort | uniq -c |awk '{i++; if(i!=1) print $2" "$1}' #swap
}
for arg do
case "$arg" in
"-a")
a=1
;;
"-r")
r=1
;;
"-v")
echo "5" #number of task is 5
exit 0
;;
"-h")
echo $help
exit 0
;;
"-?")
echo "invalid parametre, please display a help using argument h"
exit 0
;;
esac
done
#Sort according to parametres -a and -r
function sortWords {
if [[ a -eq 1 ]]; then
if [[ r -eq 0 ]]; then
clearAll | sort -nk1
fi
fi
if [[ a -eq 1 ]]; then
if [[ r -eq 1 ]]; then
clearAll | sort -nk1 -r
fi
fi
if [[ r -eq 1 ]]; then
if [[ a -eq 0 ]]; then
clearAll | sort -nk2 -r
fi
fi
if [[ a -eq 0 ]]; then
if [[ r -eq 0 ]]; then
clearAll | sort -nk2
fi
fi
}
#code is from Stackoverflow.com
function cat-all {
while IFS= read -r file
do
if [[ ! -z "$file" ]]; then
cat "$file"
fi
done
}
#histogram
hist=""
for arg do
if [[ ! -e "$arg" ]]; then
EXT=1;
echo "A FILE DOESNT EXIST" >&2
continue;
elif [[ ! -f "$arg" ]]; then
EXT=1;
echo "A FILE DOESNT EXIST" >&2
continue;
elif [[ ! -r "$arg" ]]; then
EXT=1;
echo "A FILE DOESNT EXIST" >&2
continue;
fi
done
for arg do
hist="$hist""$arg""\n"
done
echo -e "$hist" | cat-all | sortWords
exit $EXT;
Here is what our upload system which does some test to see if our program works says:
Test #6
> b5.sh -r ./easy.txt
ERROR: script output is wrong:
--- expected output
+++ script stdout
## --- line 1 (167 lines) ; +++ no lines ##
-the 89
-steam 46
-a 39
-of 37
-to 35
...
script written 484 lines, while 484 lines are expected
script error output:
A FILE DOESNT EXIST
cat: invalid option -- 'r'
Try `cat --help' for more information.
script exit value: 1
ERROR: Interrupted due to failed test
If anyone could help me I would really appreciate it.
You forgot to move the parameter index position with shift:
"-r")
r=1
shift
;;
shift above moves to the next command line arg: ./easy.txt in your case.
Without it, read -r file will read -r instead of the file name.

Check if program is running with bash shell script?

This is an example of a bash script which checks for some running process (daemon or service) and does specific actions (reload, sends mail) if there is no such process running.
check_process(){
# check the args
if [ "$1" = "" ];
then
return 0
fi
#PROCESS_NUM => get the process number regarding the given thread name
PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'
# for degbuging...
$PROCESS_NUM
if [ $PROCESS_NUM -eq 1 ];
then
return 1
else
return 0
fi
}
# Check whether the instance of thread exists:
while [ 1 ] ; do
echo 'begin checking...'
check_process "python test_demo.py" # the thread name
CHECK_RET = $?
if [ $CHECK_RET -eq 0 ]; # none exist
then
# do something...
fi
sleep 60
done
However, it doesn't work. I got "ERROR: Garbage option." for the ps command. What's wrong with these scripts? Thanks!
You can achieve almost everything in PROCESS_NUM with this one-liner:
[ `pgrep $1` ] && return 1 || return 0
if you're looking for a partial match, i.e. program is named foobar and you want your $1 to be just foo you can add the -f switch to pgrep:
[[ `pgrep -f $1` ]] && return 1 || return 0
Putting it all together your script could be reworked like this:
#!/bin/bash
check_process() {
echo "$ts: checking $1"
[ "$1" = "" ] && return 0
[ `pgrep -n $1` ] && return 1 || return 0
}
while [ 1 ]; do
# timestamp
ts=`date +%T`
echo "$ts: begin checking..."
check_process "dropbox"
[ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
sleep 5
done
Running it would look like this:
# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox
# SHELL #2
$ dropbox stop
Dropbox daemon stopped.
# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox
Hope this helps!
If you want to execute that command, you should probably change:
PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'
to:
PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)
PROCESS="process name shown in ps -ef"
START_OR_STOP=1 # 0 = start | 1 = stop
MAX=30
COUNT=0
until [ $COUNT -gt $MAX ] ; do
echo -ne "."
PROCESS_NUM=$(ps -ef | grep "$PROCESS" | grep -v `basename $0` | grep -v "grep" | wc -l)
if [ $PROCESS_NUM -gt 0 ]; then
#runs
RET=1
else
#stopped
RET=0
fi
if [ $RET -eq $START_OR_STOP ]; then
sleep 5 #wait...
else
if [ $START_OR_STOP -eq 1 ]; then
echo -ne " stopped"
else
echo -ne " started"
fi
echo
exit 0
fi
let COUNT=COUNT+1
done
if [ $START_OR_STOP -eq 1 ]; then
echo -ne " !!$PROCESS failed to stop!! "
else
echo -ne " !!$PROCESS failed to start!! "
fi
echo
exit 1

Resources