0

I have an input in my script that writes to a file needed to run some software, however the software only allows for one of 2 possible options, namely LO and LDO.

The input I already have written is at the top of the following code, and the code at the bottom is the code that was suggested that I want to manipulate

I would like to have the question "Overlap (LO or LDO): " and an error message if one of those options arent entered and to repeat that step, instead of going through the whole script again, rather than searching for values between 0 and 9

from what i can gather, I need to change the ^[0-9] to include LO and LDO, but I am not sure what punctuation or how to do it

### My Script ###
read -p "Overlap (LO or LDO): " OVERLAP

### Recommended Script ###
#!bin/bash
number=""
while [[ ! $number =~ ^[0-9]+$ ]]; do
    echo Please enter your age
    read number
done
echo You are $number years old
2

An input-and-validate loop is often written like this:

while true; do
    read -p 'Overlap (LO or LDO): ' overlap

    case $overlap in
        LO|LDO) # ok
            break
            ;;
        *) # not ok
            echo 'Please enter LO or LDO' >&2
    esac
done

I.e., you have an infinite loop that you break out of when you have validated the answer as correct.

Obviously, you could also do that as

while true; do
    read -p 'Overlap (LO or LDO): ' overlap

    if [ "$overlap" = LO ] || [ "$overlap" = LDO ]; then
        # ok
        break
    fi
    # not ok
    echo 'Please enter LO or LDO' >&2
done

Or, with a shell that has select:

echo 'Select overlap:' >&2
select overlap in LO LDO; do
    case $REPLY in
        [12]) # ok
            break
            ;;
        *) # not ok
            echo 'Please select LO or LDO' >&2
    esac
done
1

You can use the && and operator:

#! /bin/bash
overlap=""
first=1
while [[ $overlap != LO && $overlap != LDO ]] ; do
    if [[ ! $first ]] ; then
        echo 'Wrong answer, please answer LO or LDO!' >&2
    fi
    read -p 'Overlap (LO or LDO): ' overlap
    unset first
done

You can also use a regex:

until [[ $overlap =~ ^LD?O$ ]] ; do
    ...
  • ^ matches the beginning of the string
  • ? makes the previous thing optional
  • $ matches the end of the string
  • Thank you this helps me a lot. How could i go about writing an error message in that, where if LO or LDO isn't given, then an error message shows asking to repeat? sorry if im asking too much – Thomas Bates Jun 15 at 21:09
  • Check the update. – choroba Jun 15 at 21:11
  • Thank you so much, I appreciate all of this – Thomas Bates Jun 15 at 21:16
0

Another method

while read -p "Overlap (LO or LDO): " overlap;
do
 [[ "$overlap" =~ ^LD?O$ ]] && break || echo "Not LO or LDO"
done

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.