Sleep timer based on hostname

Dear all

I have a bunch of hosts which I need to run a common script. I need a sleep timee which will delay the execution based on the hostname. Usually the hostname of the servers are host01, host02 .. host16 with which I cam up with this -

#!/bin/bash
sleeptimer=$(( $(hostname -s|tr -cd 0-9|sed -e 's/^0//') * 60)) 2> /dev/null
#echo $sleeptimer

if [ -z "$sleeptimer" ]
then
	sleeptimer=$RANDOM
	while [ $sleeptimer -gt 3600 ]; do
		sleeptimer=$RANDOM
	done

fi
#sleep $sleeptimer
echo $sleeptimer

The second line works perfectly if the hostname is as previously mentioned with names host01, host02 .. host16.

What if the hostname is simply a generic name without any numbers are the end, I thought of simply generating a number.

Problem is, when the script is executed, I get this error-message

line 2: * 60: syntax error: operand expected (error token is "* 60")

I've even added "2> /dev/null" at the end of line 2 and it stlll generate the above errors. This only happens on hosts with hostnames *without* tail-numbers

Works fine otherwise :wink:

Appreciate any inputs!

end_hostname=$(hostname -s|tr -cd 0-9|sed -e 's/^0//')
if [ -z "$end_hostname" ] 
then     
  sleeptimer=$RANDOM     
  while [ $sleeptimer -gt 3600 ]; do         
    sleeptimer=$RANDOM     
  done  
else 
  sleeptimer=$(($end_hostname * 60))
fi
1 Like

I would use something like this to generate random numbers (not in relation to host names):

Just leave the alphabetic characters out and adjust the bits in the head -c .

sleeptimer=$(( $(hostname -s| awk '{if ( $0 ~ /[0-9]/) { print $0 } else { print "1" } }' | tr -cd 0-9|sed -e 's/^0//') * 60)) 2> /dev/null