LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash script problems with "if" statement (https://www.linuxquestions.org/questions/programming-9/bash-script-problems-with-if-statement-184374/)

adz 05-22-2004 01:26 AM

Bash script problems with "if" statement
 
Hi there.

I've been trying to get a script of mine working. The part that doesn't work (below) is involved with determining how long the script was running for. Here is the code:
Code:

#!/bin/sh

TOTAL_HOURS=-22
TOTAL_MINUTES=-10

#If TOTAL_HOURS is negative then add 24 to it
if [ "$(TOTAL_HOURS)" -lt "0" ];then
        TOTAL_HOURS= `expr $(TOTAL_HOURS) + 24`
fi

#If TOTAL_MINUTES is negative then add 60 to it and takeaway 1 from TOTAL_HOURS
if [ "$(TOTAL_MINUTES)" -lt "0" ];then
        TOTAL_HOURS= `expr $(TOTAL_HOURS) - 1`
        TOTAL_MINUTES= `expr $(TOTAL_MINUTES) + 60`
fi

#Formulate the total time taken into one line
TOTAL_TIME=`echo $TOTAL_HOURS`h`echo $TOTAL_MINUTES`m

#Output TOTAL_TIME to stdout
echo $TOTAL_TIME

The output I get from this is:
Code:

adz@hades:~/temp$ ./test
./test: line 1: TOTAL_HOURS: command not found
./test: line 7: [: : integer expression expected
./test: line 1: TOTAL_MINUTES: command not found
./test: line 12: [: : integer expression expected
-22h-10m

The output I want from it is just "1h50m". I've tried with and without the brackets around the variable name in the expr expression. I'm convinced it's something simple but I can't put my finger on it.

rkef 05-22-2004 02:19 AM

All I did was remove the quotes around the $VARIABLES (makes only cosmetic differences in this case) and especially the $(parentheses); $() is similar to backticks; both are forms of command substitution. You were trying to execute TOTAL_HOURS and TOTAL_MINUTES :).
Code:

#!/bin/sh

TOTAL_HOURS=-22
TOTAL_MINUTES=-10

#If TOTAL_HOURS is negative then add 24 to it
if [ $TOTAL_HOURS -lt 0 ];then
        TOTAL_HOURS=`expr $TOTAL_HOURS + 24`
fi

#If TOTAL_MINUTES is negative then add 60 to it and takeaway 1 from TOTAL_HOURS
if [ $TOTAL_MINUTES -lt 0 ];then
        TOTAL_HOURS=`expr $TOTAL_HOURS - 1`
        TOTAL_MINUTES=`expr $TOTAL_MINUTES + 60`
fi

#Formulate the total time taken into one line
TOTAL_TIME=`echo $TOTAL_HOURS`h`echo $TOTAL_MINUTES`m

#Output TOTAL_TIME to stdout
echo $TOTAL_TIME

HTH!

adz 05-22-2004 03:34 AM

Brilliant. I knew it was something simple. I was sure I tried your solution previously but maybe buggered something else up. Thanks.


All times are GMT -5. The time now is 06:14 PM.