Formulating a Case Statement for a Numeric Range

To ping numbers ranging from 25 to 125, I can use the bash pingscript. It’s a simple task that requires me to write a small case. However, the issue is that the current code only allows me to ping numbers from 0-9, and not 10-25. To overcome this problem, I can use a script that takes variables as arguments, with the first argument indicating the starting number and the second argument indicating the ending number.

Question:

I am writing a script.

case "${x_time}" in
  10) cp fileA fileB
      ;;
  20) cp fileC fileD
      ;;
  *) echo "Please check the $x_time"
      ;;
esac

Instead of using

10

and

20

, I prefer to use

1..10

and

11..20

. For example, if

$x_time is 7

is true, then the

first block

should execute, and the

18, the second block

and

21, the *)

should be used.

Is there a way to verify the roster of

$x_time

? I appreciate your help.


Solution:

Opt for tests labeled as

[[ ]]

instead.

if [[ $x_time -ge 1 && $x_time -le 10 ]]; then
    cp fileA fileB
elif [[ $x_time -ge 11 && $x_time -le 20 ]]; then
    cp fileC fileD
else
    echo "Please check the $x_time"
fi

You could also opt for utilizing

(( ))

if you desire.

if (( x_time >= 1 && x_time <= 10 )); then
    cp fileA fileB
elif (( x_time >= 11 && x_time <= 20 )); then
    cp fileC fileD
else
    echo "Please check the $x_time"
fi

Frequently Asked Questions