M2bandit
M2bandit

Reputation: 99

How do you apply two sets of multiple conditions in an if statement?

How do I seperate these two main cases from eachother? Mon or wed seperate from Tue or Fri I tried using paren but I keep getting an error

day=$(date  +%a) #day of week abrev
time=$(date +%R) #24 hour ie 17:34
dir=$(date +%F)  # %y-%m-%d
time=$(sed -e 's/://g' <<< $time) #remove : in time
dir=$(sed -e 's/-//g' <<< $dir) #remove - in YYYYMMDD
if [ $day == 'Mon' ] || [ $day == 'Wed' ] && [ $time -gt 1150 ] && [ $time -lt 1250 ] || 
 [ $day == 'Tue' ] || [ $day == 'Fri' ] &&  [ $time -gt 1730 ]  && [ $time -lt 1900 ] 
then
mkdir -p 444/$dir
cd 444/$dir
fi;

Upvotes: 1

Views: 48

Answers (3)

chepner
chepner

Reputation: 531055

You can simplify this by defining a range based on the value of $day; then you have one simple comparison to make.

case $day in
  Mon|Wed) low=1150; high=1250;;
  Tue|Thu) low=1730; high=1900;;
  *) low=2359; high=0000;;  # Non-matching days create an impossible-to-match time
esac

if (( low < time && time < high )); then
  mkdir -p "444/$dir" && cd "444/$dir"
fi

Upvotes: 0

Inian
Inian

Reputation: 85560

You could use the [[ operator in bash which is the improvement over the [ command. It has several enhancements that make it a better choice if you write scripts that target bash. Use its =~ regex operator for doing regular expression matches and the arithmetic context operator (( )) your conditions can be brought down to

time=$(date "+%H%M") # to list time from 0000 to 2359
if ( [[ $day =~ ^(Mon|Wed)$ ]] && (( time <= 1150 && time >= 1250 )) ) || \
   ( [[ $day =~ ^(Tue|Fri)$ ]] && (( time <= 1730 && time >= 1900 )) ); then
    echo "your actions here"
fi

Upvotes: 1

DaBernMon
DaBernMon

Reputation: 48

One option is to use [[ instead of [. This will then allow you to use ( and ) to group the separate conditions.

So in your example:

if [[ ( $day == 'Mon' || $day == 'Wed' ) && ( $time -gt 1150 && $time -lt 1250 ) ]] || 
   [[ ( $day == 'Tue' || $day == 'Fri' ) && ( $time -gt 1730 && $time -lt 1900 ) ]]
then
    # Do stuff
fi

I don't believe [[ is always POSIX compliant but it should work using bash.

Upvotes: 2

Related Questions