Using case for a range of numbers in Bash

前端 未结 5 754
忘掉有多难
忘掉有多难 2020-11-29 06:59

I am trying to do the following using case in Bash (in Linux).

If X is between 460 and 660, output X information.

If X is between 661 and 800, d

5条回答
  •  春和景丽
    2020-11-29 07:16

    I was looking for the simplest solution and found it difficult to use a case statement with a number range .

    Finally i found a really simple solution for zsh :

      #!/usr/bin/zsh 
    
     case "${var}" in
    
     <0-5461>)
    
     printf "${var} is between 0 and 5461"
    
     ;;
    
     <5462-10922>)
    
    printf "${var} is between 5462-10922"
    
     ;;
    
     esac
    

    and for Bash :

      #!/bin/bash
    
     case $((   
    
    (var >= 0 && var <= 5461)      * 1 +   
    
    (var > 5462 && var  <= 10922)   * 2)) in   
    
    (1) printf "${var} is between 0 and 5461";; 
    
    (2) printf "${var} is between 5461 and 10922";; 
    
    esac
    

    Hope it helps someone .

提交回复
热议问题