-   Programming (
-   -   BASH - Read a txt and do an 'if' statement (

emmeteo 01-10-2013 12:36 PM

BASH - Read a txt and do an 'if' statement
Hi everyone.
I didn't know how to be more specific in the subject.
Here's the issue:

I have sincronized google calendar with conky. I have a crontab that every hour runs this script :


gcalcli --nc agenda | tee ~/gcal.txt

The script above goes on the internet and copy my nextfivedays agenda in gcal.txt. Then, conky reads that file and shows on desktop the appointments.
Sometimes, wheh my internet connection is down, the bash script writes the following line in gcal.txt: Error. No internet connection!.

I would like to add an if statement in the bash script to do something like:

1. run the previous command;
2. create a new text file called gcalconky.txt;
3. if gcal.txt is empty, then write "None" in gcalconky.txt;
4. if gcal.txt contains the sentence "Error. No internet connection!", then don't do anything;
5. else (if gcal.txt contains some random text), simply copy gcal.txt's content in gcalconky.txt.

In this way, also if I have no connection, I will see on my desktop the appointments that have been saved during the previous action of the crontab.
I hope I was clear, otherwise I'll try to be clearer.
Thank you all.

steelneck 01-10-2013 01:23 PM


touch calconky.txt
if [ ! -s gcal.txt ]
 echo "None" > calconky.txt
if grep -v "Error. No internet connection!" gcal.txt
 cp gcal.txt calconky.txt

unSpawn 01-10-2013 01:32 PM


#!/bin/bash --
# Set debug and error mode while testing, set default behaviour and use 'mktemp':
set -vx; LANG=C; LC_ALL=C; export LANG LC_ALL
_MYTMPDIR=`mktemp -p /tmp -d gcalcli.XXXXXXXXXX` && {
 gcalcli --nc agenda > "${_MYTMPDIR}/gcal.out" 2> "${_MYTMPDIR}/gcal.err"
 [ -s "${_MYTMPDIR}/gcal.out" ] || echo None > ~/gcalconky.txt
 grep -q "Error. No internet connection" "${_MYTMPDIR}/gcal.err"\
 || install "${_MYTMPDIR}/gcal.out" -m 0640 ~/gcalconky.txt
}; rm -rf "${_MYTMPDIR}"
exit 0

emmeteo 01-10-2013 03:09 PM

Thank you very much both.
I solved my problem.

All times are GMT -5. The time now is 04:19 PM.