Using case for a range of numbers in Bash

前端 未结 5 766
忘掉有多难
忘掉有多难 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:17

    Similar issue which might be useful to someone ... Random additional thing I just tried out where it checks also that it is an integer, for me I wanted it to have a preset value, let the user change it, if they input the wrong data it sets to default.

        func_set_num_files(){
            echo "How many files do you want to create? (input a number 1-10000)"
            read X
            # 1, is it a number, #2 is it within max range?
            if [[ $X != *[!0-9]* ]]; then
    
                if ((1<=X && X<=10000)) ;then
                            echo "NUM_FILES=$X"
                            NUM_FILES=$X
                    else
                            echo "Invalid input, setting to default value [ $NUM_FILES ].";sleep 3
                fi
    
            else
                echo "Invalid input, non-numeric values entered, setting to default value [ $NUM_FILES ].";sleep 3
            fi
    
        }
    

    Another example using 'case' to check that a variable is in a range of integers :

    check that $MAX is a number and that it's between 50-100 :

                case $MAX in
                    ''|*[!0-9]*)
                        echo "The value $MAX is not a number !"
                        exit 1
                    ;;
                    *)
                        if [ $MAX -lt 50 ] || [ $MAX -gt 100 ] ;then
                            echo "The value $MAX is not between 50-100"
                            exit 1
                        fi
                        echo "Looks like we are good !"
                    ;;
                esac
    

提交回复
热议问题