0

I have this menu but the option to give the user an error if the input text is wrong doesn´t work.

if  [ -n "$1" -a -n "$2" -a -f "$1" ]
then

dts=($(cat $1 | cut -d: -f$2))

        for i in ${!dts[@]}
        do
                echo "$i) ${dts[$i]} "
        done

        read   -p "Select a user to delete: " OKSELUSRGRP
        p=$( echo $OKSELUSRGRP | grep -E ^[0-${#dts[@]}]$ )

                if [  -n "$p" ]
                then
                OKSELUSRGRP=${dts[$p]}
                else
                OKSELUSRGRP=""
                fi

else
        echo "Error, select a correct option"
        sleep 1
fi

Any ideas?

Thanks!

  • You want it to error out if the user sets an invalid value to OKSELUSRGRP correct? The way it currently is written the only way that echo "Error, select a correct option" && sleep 1 will be executed is if: $1 is null or $2 is null or $1 is not a file. The check for validity happens within that first if statement so that's where you would need to put the error. – jesse_b Aug 31 '17 at 1:06
1

Maybe try something like this, although I'm not quite sure what your script is doing.

if  [ -n "$1" -a -n "$2" -a -f "$1" ]; then
    dts=($(cat $1 | cut -d: -f$2))
        for i in ${!dts[@]}; do
            echo "$i) ${dts[$i]} "
        done
        read -p "Select a user to delete: " OKSELUSRGRP
        p=$(echo $OKSELUSRGRP | grep -E ^[0-${#dts[@]}]$)
        while [ -z "$p" ]; do
            echo "Error, select a correct option"
            sleep 1
            read -p "Select a user to delete: " OKSELUSRGRP
            p=$(echo $OKSELUSRGRP | grep -E ^[0-${#dts[@]}]$)
        done
    OKSELUSRGRP=${dts[$p]}
else
        echo "
Usage: $0 [file] [something else]   

$0 can be used to select users or something.
"
fi
  • You are a genius!! Thanks you very much!!!!!!!!! – chelomvd Aug 31 '17 at 1:23
  • NP, glad I could help. while loops are my go-to when forcing users to give a specific input although I guess an until loop could be used just the same (except opposite). – jesse_b Aug 31 '17 at 1:25
  • 1
    Hmmm. Seems like this might break if ${#dts[@]} is greater than 9. – Scott Aug 31 '17 at 7:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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