0

I need to write a Bash script that source another script (config script) for hours. If the hour mentioned in config script matches the Linux past hour it needs to print the hour.

$ cat ConfHours.sh
#!/bin/bash --

Hours=(0 1 2 22 23)

$ cat Foo.sh

#!/bin/bash --
source /home/Geo/ConfHours.sh
arrayHours=( ${HOURS} )
for v in "${arrayHours[@]}"
do
HOUR=$(( $(date +%H) -1))
if [ "${HOUR}" == "v" ] ; then
HOUR = ${HOUR}
echo $HOUR
fi
done

When I run Foo.sh, I do not get anything. Could you please correct me where I am wrong?

Braiam
  • 1
  • 11
  • 47
  • 78
Raj baba
  • 61
  • 7
  • 2
    `HOURS` is already an array. When you use `${HOURS}` you are only getting the first value from that array so `arrayHours` contains just one value, the first value. – Etan Reisner Jan 11 '15 at 23:47

1 Answers1

2

Some errors:

source /home/Geo/ConfHours.sh
arrayHours=( ${HOURS} )

ConfHours defines a variable named Hours -- different variable

for v in "${arrayHours[@]}"
do
HOUR=$(date -d "1 hour ago" +%H)

You don't need to define this every time through the loop: put it before the for statement

if [ "${HOUR}" == "v" ] ; then
  • missing $ for the v variable
  • $HOUR will contain a leading 0 (due to %H)
  • a better test: if (( 10#$HOUR == 10#$v ))
HOUR = ${HOUR}

No spaces around the = allowed for variable assignment. Why are you trying to redefine the variable to itself?

echo $HOUR
fi
done

A more concise way to test an array contains a value is to take advantage of array string concatenation and pattern matching:

source ConfHours.sh
hour=$(date +%k)           # leading space, not leading zero
if [[ " ${Hours[*]} " == *" ${hour# } "* ]]; then 
    echo "$hour"
fi

All spaces and quotes are required.

Don't use UPPER_CASE_VARS: here's why

Community
  • 1
  • 1
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Doesn't that concat test have substring matching problems if the array contains spaces in the values? – Etan Reisner Jan 11 '15 at 23:53
  • I am trying to compare previous hour e.g. right now is hour 23 I want to compare hour 22 from config file with current Linux hour. Could you please show me how to fix my code? Your code works when I do: hour=$(( $(date +%k) -1)) ; When I run script at hour 00 it should compare hour 23 from config file. – Raj baba Jan 12 '15 at 00:04
  • This is my updated script: arrayHours=( ${HOURS} ) for v in "${arrayHours[@]}" do HOUR=$(( $(date +%H) -1)) if [ "${HOUR}" == "$v" ] ; then HOUR=${HOUR} echo $HOUR fi done – Raj baba Jan 12 '15 at 00:05
  • Looks like you're ignoring all of my advice. What do you think this accomplishes: `HOUR=${HOUR}` ?? To answer your question: `hour=$(date -d "1 hour ago" +"%H")` – glenn jackman Jan 12 '15 at 00:42
  • @EtanReisner, you're quite right. This array holds integers. – glenn jackman Jan 12 '15 at 00:45