Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have some data spread over time intervals, and I want to take some of those data within the time intervals. For example, I have data at times within 1..9, 11..19, etc., and I want to take data within 1-2, then 11-12, etc. This will be part of a more complex bash script, in which I want to include this condition, with a if cycle, to isolate the times where I can catch the data.

I was thinking something like:

if (( $t_initial & $t_final )) in (begin1, fin1) or in (begin2, fin2) ...

where t_initial and t_final are calculated separately, by the script itself.

I can not write this condition in bash syntax. I found some other solutions, but they seem extremely long and inconvenient, so I am here to ask simpler and more readable solutions.

share|improve this question
    
I don't get it. Data should have a single timestamp, why do you have 2 variables t_initial and t_final? –  LatinSuD Jun 27 at 9:18
    
@LatinSuD, Because I am working in phase, more than times, and I have to get only same phase intervals between given time intervals :) –  Py-ser Jun 27 at 9:26
    
What happens if t_initial=1, t_final=3, begin1=2,fin1=4? Is that a match or not? –  LatinSuD Jun 27 at 9:27
    
@LatinSuD, no it is not. begin and fin are intended to be the extreme times of a given interval. if the times are not within the intervals, then the condition is not satisfied. –  Py-ser Jun 27 at 9:29
add comment

1 Answer

Not sure if you would like this solution. It has 2 features:

  • No external programs are required
  • It uses a function, so at least it hides the complexity of the comparisons

This is it:

#!/bin/bash

# The comparing function
function compareInterval {
 t1=$1
 t2=$2

 shift 2

 while (( "$2" )); do
   if ((  $t1 >= $1  &&  $t2 <= $2 )); then
     # got match
     return 0
   fi
   shift 2
 done

 return 1
}

# sample values
t_initial=2
t_final=4

# Invocation. Compares against 1-3, 3-5, 2-5
if compareInterval  $t_initial $t_final  1 3  3 5  2 5; then
 echo Got match
fi
share|improve this answer
    
Thanks a lot! I have never used functions in bash, could you tell me the logic behind the separation of the comparison? how can it understand to compare between 1 and 3, and not between, i.e., 3 and 3, or 5 and 2 (in the example above)? –  Py-ser Jun 27 at 10:50
    
Separation is cosmetic only. The important thing is parameter number. They are processed in pairs. –  LatinSuD Jun 27 at 11:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.