I've been working on a bash script to change my background depending on the time of day but I can't figure out why the background is always changed to dawn even if the time is Noon.
#!/bin/bash
date=$(date "+%H")
DawnNum=$(seq -s " -o " 5 9)
DayNum=$(seq -s " -o " 10 17)
DuskNum=$(seq -s " -o " 18 22)
NightNum=$(seq -s " -o " 23 24)
NightNumCont=$(seq -s " -o " 0 4)
if
[ -e ~/.cache/weather.txt ] ;
then
rm ~/.cache/weather.txt ;
else
echo "Cache is clean." ;
fi
curl -o ~/.cache/weather.txt -s "https://weather.yahooapis.com/forecastrss?w=2470169&u=f" ;
cat ~/.cache/weather.txt | grep Rain -n | grep 29 || cat ~/.cache/weather.txt | grep Snow -n | grep 29 ;
current=$?
if
[ "$current" -eq 0 ] && [ "$date" -eq $DawnNum -o $DayNum ] ; then
gsettings set org.cinnamon.desktop.background picture-uri "file:///home/user/Pictures/Google Now/mountains-stormday.png" ;
elif
[ "$current" -eq 0 ] && [ "$date" -eq $DuskNum -o $NightNum ] ; then
gsettings set org.cinnamon.desktop.background picture-uri "file:///home/user/Pictures/Google Now/mountains-stormnight.png" ;
elif
[ "$current" -ne 0 ] && [ "$date" -eq $DawnNum ] ; then
gsettings set org.cinnamon.desktop.background picture-uri "file:///home/user/Pictures/Google Now/mountainsdawn.png" ;
elif
[ "$current" -ne 0 ] && [ "$date" -eq $DayNum ] ; then
gsettings set org.cinnamon.desktop.background picture-uri "file:///home/user/Pictures/Google Now/mountainsday.png" ;
elif
[ "$current" -ne 0 ] && [ "$date" -eq $DuskNum ] ; then
gsettings set org.cinnamon.desktop.background picture-uri "file:///home/user/Pictures/Google Now/mountainsdusk.png" ;
elif
[ "$current" -ne 0 ] && [ "$date" -eq $NightNum ] ; then
gsettings set org.cinnamon.desktop.background picture-uri "file:///home/user/Pictures/Google Now/mountainsnight.png" ;
else
gsettings set org.cinnamon.desktop.background picture-uri "file:///home/user/Pictures/Google Now/sanfranciscodawn.png" ;
fi
exit
I would recommend simplifying your logic and reducing repetition in your code. As you are using bash and working with integers, you can use (( )) numerical tests to determine what time range you are within. This kind of test doesn't require you to use $ variable names and expresses your meaning a little more clearly:
#!/bin/bash
date=$(date "+%H")
dawn_start=5
day_start=10
dusk_start=18
night_start=23
# ...
current=$?
if [[ "$current" == 0 ]]; then
if (( date >= dawn_start )) && (( date < dusk_start )); then
uri="mountains-stormday.png"
else
uri="mountains-stormnight.png"
fi
else
if (( date >= dawn_start )) && (( date < day_start )); then
uri="mountainsdawn.png"
elif (( date >= day_start )) && (( date < dusk_start )); then
uri="mountainsday.png"
elif (( date >= dusk_start )) && (( date < night_start )); then
uri="mountainsdusk.png"
elif (( date >= night_start )) || (( date < dawn_start )); then
uri="mountainsnight.png"
fi
fi
# catch-all, if $uri hasn't been set
[[ -z "$uri" ]] && uri="sanfranciscodawn.png"
dir="file:///home/user/Pictures/Google Now"
gsettings set org.cinnamon.desktop.background picture-uri "$dir/$uri"
This doesn't do what you expect:
[ "$date" -eq $DawnNum -o $DayNum ]
The problem is that -eq binds more tightly than -o.
A simpler test that might do what you are aiming for is:
[ "$date" -ge 5 ] && [ "$date" -le 17 ]
Related
Im trying to get an array from grades.txt, and determine what letter grade it should be assigned.
I either get
hw4part2.sh: line 26: [: : integer expression expected
If i use -ge or
hw4part2.sh: line 26: [: : unary operator expected
If i use >=
Below is the code im trying to get working
mapfile -t scores < grades.txt
numOScores=0
numOA=0
numOB=0
numOC=0
numOD=0
numOF=0
DoneWScores=0
A=90
B=80
C=70
D=60
F=59
while [ $DoneWScores -eq 0 ]
do
numOScores=$((numOScores + 1))
if [ "${scores[$numOScores]}" -ge "$A" ]
then
echo "A"
elif [ "${scores[$numOScores]}" -ge "$B" ]
then
echo "B"
elif [ "${scores[$numOScores]}" -ge "$C" ]
then
echo "C"
elif [ "${scores[$numOScores]}" -ge "$D" ]
then
echo "D"
elif [ "${scores[$numOScores]}" -le "$F" ]
then
echo "F"
else
echo "Done/error"
DoneWScores=1
fi
done
If anyone knows what my problem is, that'd be greatly appreciated
Consider this:
#!/usr/bin/env bash
if (( ${BASH_VERSINFO[0]} < 4 )); then
echo "Bash version 4+ is required. This is $BASH_VERSION" >&2
exit 1
fi
letterGrade() {
if (( $1 >= 90 )); then echo A
elif (( $1 >= 80 )); then echo B
elif (( $1 >= 70 )); then echo C
elif (( $1 >= 60 )); then echo D
else echo F
fi
}
declare -A num
while read -r score; do
if [[ $score == +([[:digit:]]) ]]; then
grade=$(letterGrade "$score")
(( num[$grade]++ ))
echo "$grade"
else
printf "invalid score: %q\n" "$score"
fi
done < grades.txt
for grade in "${!num[#]}"; do
echo "$grade: ${num[$grade]}"
done | sort
I am trying to test if a number is in the interval [1;100] here is what I did:
var=10
if [ $["$var" -gt "1" ] -a $["$var" -lt "100"] ] ; then
echo "yes"
else
echo "no"
fi
however when I run the script I get the error message:
./yourscript:line 2 10 -gt 1:error syntax in expression ,any ideas why?
delete unnecessaries and use &&:
var=10
if [ $var -gt 1 ] && [ $var -lt 100 ] ; then #or with -a if [ $var -gt 1 -a $var -lt 100 ] ;
echo "yes"
else
echo "no"
fi
How to compare two timestamps along with another condition.
Please find below code as an trial for the work around.
d=$(date +%Y%m%d) #Today
d1=$(date +%b" "%d) #Centre1 col 1 & 2 (MON DD)
ct=$(date +'%H%M%S') #Current Time (HHMM)
t01='013000'
t02='033000'
t03='053000'
t04='073000'
find . -mtime 0 -iname "RBDEXT*.csv" -ls | awk '{printf("%-5s%s\t%-40s%s\t%s\t\n", $8,$9,$11,$10,$7)}' > rbdextmp1.txt
rbdextCO=$(wc -l rbdextmp1.txt | awk '{print $1}')
rbdextIN=$(cat rbdextmp1.txt | grep "inprogress" | wc -l)
touch centre.txt
if [[ [ "$rbdextIN" -eq 0 ] &&
[ [ "$ct" -gt "$t01" ] && [ "$ct" -lt "$t02" ] && [ "$rbdextCO" -eq 1 ] ||
[ "$ct" -gt "$t02" ] && [ "$ct" -lt "$t03" ] && [ "$rbdextCO" -eq 2 ] ||
[ "$ct" -gt "$t03" ] && [ "$ct" -lt "$t04" ] && [ "$rbdextCO" -eq 3 ] ]
]]
then
echo "$d1 RBDEXT.$d.csv($rbdextCO) OK" >> centre.txt
elif [ "$rbdextIN" -ge 1 ]
then
echo "$d1 RBDEXT.$d.csv($rbdextCO) OKBUT" >> centre.txt
else
echo "$d1 RBDEXT.$d.csv($rbdextCO) NOK" >> centre.txt
fi
Could you please help me on this please, Thanks a lot !
I suggest you build up to this slowly.
Start with:
if [ "2" -gt "1" ]
then
echo "Green"
else
echo "Red"
fi
... check that it works. Then add a second clause using &&, resolve any syntax problems, make sure it works. Then replace your hard-coded values with variables. Then populate the variables with output from date. Check that it still works after each step. You'll get there.
Bonus tip -- backticks for command substitution have been frowned upon for some time, because it's easy to make mistakes. Use currentTime=$(date +%H%M%S) instead.
It sounds like this is what you want:
currenttime=$(date +'%H%M%S')
dayofweek=$(date +'%u')
time1='013000'
time2='033000'
time3='053000'
time4='073000'
count=$(wc -l < xxx.txt)
if (( (dayofweek == 1) &&
( ( (currenttime > time1) && (currenttime < time2) && (count == 1) ) ||
( (currenttime > time2) && (currenttime < time3) && (count == 2) ) ||
( (currenttime > time3) && (currenttime < time4) && (count == 3) ) )
))
then
color="GREEN"
else
color="RED"
fi
printf 'GP_GLOBAL_FEED(%s) %s\n' "$count" "$color" |
mailx -s "$color" abcd#mail.com
#!/bin/bash
echo "Enter three numbers and this program will give you the middle number : " ; read num1 ; read num2 ; read num3
if [ "$num1" -gt "$num2" ] && [ "$num1" -lt "$num3" ] || [ "$num1" -lt "$num2" ] && [ "$num1" -gt "$num3" ]; then
{
echo "The middle number is $num1"
}
elif [ "$num2" -gt "$num1" ] && [ "$num2" -lt "$num3" ] || [ "$num2" -lt "$num1" ] && [ "$num2" -gt "$num3" ]; then
{
echo "The middle number is $num2"
}
elif [ "$num3" -gt "$num1" ] && [ "$num3" -lt "$num2" ] || [ "$num3 -lt "$num1" ] && [ "$num3" -gt "$num2" ]; then
{ echo "The middle number is $num3" }
fi
The problem I have is with the or condition. I input the numbers 1, 2, and 3, but I get the middle number as 1 all the time.
How about this:
getmid() {
if (( $1 <= $2 )); then
(( $1 >= $3 )) && { echo $1; return; }
(( $2 <= $3 )) && { echo $2; return; }
fi;
if (( $1 >= $2 )); then
(( $1 <= $3 )) && { echo $1; return; }
(( $2 >= $3 )) && { echo $2; return; }
fi;
echo $3;
}
# All permutations of 1, 2 and 3 print 2.
getmid 1 2 3
getmid 2 1 3
getmid 1 3 2
getmid 3 1 2
getmid 2 3 1
getmid 3 2 1
This one should work:
#!/bin/bash
echo "Enter three numbers and this program will give you the middle number : " ; read num1 ; read num2 ; read num3;
if [ "$num1" -gt "$num2" ] && [ "$num1" -lt "$num3" ]; then
{
echo "The middle number is" $num1 ;
}
elif [ "$num1" -lt "$num2" ] && [ "$num1" -gt "$num3" ]; then
{
echo "The middle number is" $num1 ;
}
elif [ "$num2" -gt "$num1" ] && [ "$num2" -lt "$num3" ]; then
{
echo "The middle number is" $num2 ;
}
elif [ "$num2" -lt "$num1" ] && [ "$num2" -gt "$num3" ]; then
{
echo "The middle number is" $num2 ;
}
elif [ "$num3" -gt "$num1" ] && [ "$num3" -lt "$num2" ]; then
{
echo "The middle number is" $num3 ;
}
elif [ "$num3" -lt "$num1" ] && [ "$num3" -gt "$num2" ]; then
{
echo "The middle number is" $num3 ;
}
fi
I am completely lost as to why this error keeps happening, I am fairly certain that I am using the correct syntax, however, every time I execute this BASH script, I get the following error:
/home/clucky/MCServerBackup/MCServerBackup.sh: line 200: syntax error near unexpected token `'2''
/home/clucky/MCServerBackup/MCServerBackup.sh: line 200: ` logInfo() '2' "none" "Minecraft: $minecraftsize.$minecraftsized $minecraftunit"'
The line in particular that it appears to be refrencing is line 200, which is where the code attempts to execute the function logInfo() as follows:
logInfo() '2' "none" "Minecraft: $minecraftsize.$minecraftsized $minecraftunit"
In the above line of code, 2 is the indent level (2 x 5 spaces). none tells the function to ignore the logLevel that is specified in the configuration and log it anyway. Minecraft: $minecraftsize...$minecraftunit is what is being added into the log file, which the words preceeded by a $ are of course variables. The entire code can be viewed below.
#! /usr/bin/env bash
#Declare Functions
logInfo() {
if [ "$logInFile" == "true" ] || [ "$logInConsole" == "true" ] ; then
let tabAmount=5*$1
indent=""
for (( indentrepeat=0; indentrepeat < $tabAmount; indentrepeat++ ))
do
indent="$indent "
done
if [ "$2" == "none" ] ; then
infoItem="$3"
else
if [ "$logLevel" == "high" ] ; then
if [ "$2" == "subtask" ] ; then
#High + Subtask
infoItem="`date '+%H:%M:%S'` $3"
elif [ "$2" == "task" ] ; then
#High + Task
infoItem="`date '+%H:%M:%S'` $3"
fi
elif [ "$logLevel" == "medium" ] ; then
if [ "$2" == "subtask" ] ; then
#Medium + Subtask
infoItem="$3"
elif [ "$2" == "task" ] ; then
#Medium + Task
infoItem="`date '+%H:%M:%S'` $3"
fi
else
if [ "$2" == "subtask" ] ; then
#Low + Subtask
infoItem=''
elif [ "$2" == "task" ] ; then
#Low + Task
infoItem="$3"
fi
fi
fi
if [ "$logInFile" == "true" ] ; then
echo -e "$indent$infoItem" >> backup.log
fi
if [ "$logInConsole" == "true" ] ; then
echo -e "$indent$infoItem"
fi
fi
}
logError() {
if [ "$logInFile" == "true" ] || [ "$logInConsole" == "true" ] ; then
let tabAmount=5*$1
indent=""
for (( indentrepeat=0; indentrepeat < $tabAmount; indentrepeat++ ))
do
indent="$indent "
done
if [ "$logInFile" == "true" ] && [ "$logErrors" == "true" ] ; then
echo -e "$indent[ERROR] $2" >> backup.log
fi
if [ "$logInConsole" == "true" ] && [ "$logErrors" == "true" ] ; then
echo -e "$indent[ERROR] $2"
fi
fi
}
#Set Variables
source config.sh
minecraftsize=0
sqlsize=0
websitesize=0
timedate=`date '+%m.%d.%Y-%H:%M'`
#Update
if [ $version != "1.0.0" ] ; then
source update.sh
fi
#Trigger General Settings
echo -ne "\033]0;$serverName - Backup\007"
if [ "$serverDirectory" == "default" ] ; then
BINDIR="$(dirname "$(readlink -fn "$0")")"
cd "$BINDIR"
else
if [ -d "$serverDirectory" ] ; then
cd "$serverDirectory"
else
directoryExists=false
echo '$serverDirectory defined as '"$serverDirectory"' does not exist. Please double check your configuration and make sure this folder exists.'
if [ "$logInFile" == "true" ] ; then
echo "-------------- `date '+%d-%B-%Y %H:%M'` --------------" >> backup.log
echo -e ' [ERROR] $serverDirectory defined as '"$serverDirectory"', does not exist. Please double check your configuration and make sure this folder exists.'"\n" >> backup.log
fi
fi
fi
if [ "$purgeFiles" == "true" ] || [ "$backupMinecraft" == "true" ] || [ "$backupMySQL" == "true" ] || [ "$backupWebsite" == "true" ] && [ "$directoryExists" != "false" ] ; then
echo "-------------- `date '+%d-%B-%Y %H:%M'` --------------" >> backup.log
#Create Directories
echo "[`date '+%H:%M:%S'`] Directory Creation Started" >> backup.log
if [ ! -d ".backups" ] ; then
mkdir -p .backups
fi
mkdir -p .backups/$timedate
if [ "$backupMySQL" == "true" ] ; then
mkdir -p .backups/$timedate/MySQL
fi
if [ "$backupWebsite" == "true" ] ; then
mkdir -p .backups/$timedate/Website
fi
if [ "$backupMinecraft" == "true" ] ; then
mkdir -p .backups/$timedate/MinecraftServers
fi
echo "[`date '+%H:%M:%S'`] Directory Creation Completed" >> backup.log
#Backup Minecraft Servers
if [ "$backupMinecraft" == "true" ] ; then
echo "[`date '+%H:%M:%S'`] Minecraft Backup Started" >> backup.log
for (( servercount = 0; servercount < ${#mcservers[#]}; servercount++ ))
do
echo " ${mcservers[servercount]}" >> backup.log
tar -zcpf .backups/$timedate/MinecraftServers/${mcservers[servercount]}.tar.gz --directory ${mcservers[servercount]} ${fileexcludes[servercount]} .
minecraftsize=`expr $minecraftsize + $(ls -la .backups/$timedate/MinecraftServers/${mcservers[servercount]}.tar.gz | awk '{ print $5}')`
done
echo "[`date '+%H:%M:%S'`] Minecraft Backup Completed" >> backup.log
fi
#Copy MySQL Databases
if [ "$backupMySQL" == "true" ] ; then
echo "[`date '+%H:%M:%S'`] MySQL Backup Started" >> backup.log
for (( sqlcount = 0; sqlcount < ${#sqldatabases[#]}; sqlcount++ ))
do
if [[ "${sqldatabases[sqlcount]}" =~ # ]] ; then
sqldatabases[sqlcount]=${sqldatabases[sqlcount]//[#]/}
mysqldump -u"$sqluser" -p"$sqlpass" -h"$sqlhost" ${sqldatabases[sqlcount]} > .backups/$timedate/MySQL/${sqldatabases[sqlcount]}.sql;
sqlsize=`expr $sqlsize + $(ls -la .backups/$timedate/MySQL/${sqldatabases[sqlcount]}.sql | awk '{ print $5}')`
echo " ${sqldatabases[sqlcount]}*" >> backup.log
else
mysqldump -u"$sqluser" -p"$sqlpass" -h"$sqlhost" --skip-lock-tables ${sqldatabases[sqlcount]} > .backups/$timedate/MySQL/${sqldatabases[sqlcount]}.sql;
sqlsize=`expr $sqlsize + $(ls -la .backups/$timedate/MySQL/${sqldatabases[sqlcount]}.sql | awk '{ print $5}')`
echo " ${sqldatabases[sqlcount]}" >> backup.log;
fi
done
fi
#Backup Website
if [ "$backupWebsite" == "true" ] ; then
echo "[`date '+%H:%M:%S'`] Website Backup Started" >> backup.log
if [ "$websiteDirectory" == "default" ] ; then
websiteDirectory=var/www/
fi
if [ -d "$websiteDirectory" ] ; then
tar -zcpf .backups/$timedate/Website/website.tar.gz --directory $websiteDirectory $websiteExcludes .
echo "[`date '+%H:%M:%S'`] Website Backup Completed" >> backup.log
else
logError "5" "\0044websiteDirectory defined as $websiteDirectory does not exist. Please double check your configuration and make sure this folder exists."
echo "[`date '+%H:%M:%S'`] Website Backup Cancelled" >> backup.log
fi
fi
#Purge files 3 days old
if [ "$purgeFiles" == "true" ] ; then
echo "[`date '+%H:%M:%S'`] Purging Old Backups" >> backup.log
find .backups* -mmin +$purgeTime -exec rm --recursive {} \;
echo "[`date '+%H:%M:%S'`] Purging Complete" >> backup.log
fi
#Read back file size
let filesize=$minecraftsize+$sqlsize+$websitesize
if [ "$filesize" -ge 1024 ] ; then
if [ "$filesize" -ge 1048576 ] ; then
if [ "$filesize" -ge 1073741824 ] ; then
filedivider=1073741824
fileunit="GB"
else
filedivider=1048576
fileunit="MB"
fi
else
filedivider=1024
fileunit="KB"
fi
else
filedivider=1
fileunit="Bytes"
fi
let filesized='(''('$filesize%$filedivider')'*100')'/$filedivider
let filesize=$filesize/$filedivider
echo " Total Compression Size: $filesize.$filesized $fileunit" >> backup.log
if [ "$backupMinecraft" == "true" ] ; then
if [ "$minecraftsize" -ge 1024 ] ; then
if [ "$minecraftsize" -ge 1048576 ] ; then
if [ "$minecraftsize" -ge 1073741824 ] ; then
minecraftdivider=1073741824
minecraftunit="GB"
else
minecraftdivider=1048576
minecraftunit="MB"
fi
else
minecraftdivider=1024
minecraftunit="KB"
fi
else
minecraftdivider=1
minecraftunit="Bytes"
fi
let minecraftsized='(''('$minecraftsize%$minecraftdivider')'*100')'/$minecraftdivider
let minecraftsize=$minecraftsize/$minecraftdivider
logInfo() '2' "none" "Minecraft: $minecraftsize.$minecraftsized $minecraftunit"
fi
if [ "$backupMySQL" == "true" ] ; then
if [ "$sqlsize" -ge 1024 ] ; then
if [ "$sqlsize" -ge 1048576 ] ; then
if [ "$sqlsize" -ge 1073741824 ] ; then
sqldivider=1073741824
sqlunit="GB"
else
sqldivider=1048576
sqlunit="MB"
fi
else
sqldivider=1024
sqlunit="KB"
fi
else
sqldivider=1
sqlunit="Bytes"
fi
let sqlsized='(''('$sqlsize%$sqldivider')'*100')'/$sqldivider
let sqlsize=$sqlsize/$sqldivider
echo " MySQL: $sqlsize.$sqlsized $sqlunit" >> backup.log
fi
if [ "$backupWebsite" == "true" ] ; then
if [ "$websitesize" -ge 1024 ] ; then
if [ "$websitesize" -ge 1048576 ] ; then
if [ "$websitesize" -ge 1073741824 ] ; then
websitedivider=1073741824
websiteunit="GB"
else
websitedivider=1048576
websiteunit="MB"
fi
else
websitedivider=1024
websiteunit="KB"
fi
else
websitedivider=1
websiteunit="Bytes"
fi
let websitesized='(''('$websitesize%$websitedivider')'*100')'/$websitedivider
let websitesize=$websitesize/$websitedivider
echo " Website: $websitesize.$websitesized" >> backup.log
fi
echo "" >> backup.log
fi
As I stated earlier, I am completely lost, so any assistance would be greatly appreciated. Thank you!
You don't invoke a function with parentheses. Change:
logInfo() '2' "none" "Minecraft: $minecraftsize.$minecraftsized $minecraftunit"
to
logInfo '2' "none" "Minecraft: $minecraftsize.$minecraftsized $minecraftunit"