Elliot Reed
Elliot Reed

Reputation: 749

IF statement in BASH isn't doing what's expected

Got a very simple script which checks barcodes basically. There's two barcodes that have to be checked that they are not confused when being made into a variable.

Basically the first barcode should contain only numbers 0-9, and the second barcode should contain two letters, then some numbers, then two more letters, like AB123456789CD.

If they're confused and read in the wrong order then it plays an error sound. This is what I have so far, the top one's working, but I'm not sure it it's the best solution, and the bottom one doesn't do what I want:

echo -e $BLUE"Please scan the first barcode"$ENDCOLOUR
read -p "Barcode: " BARCODE1
if [[ "$BARCODE1" =~ [a-z] ]] ; then
play -q ./error.wav
else

echo -e $BLUE"Please scan the second barcode"$ENDCOLOUR
read -p "Barcode: " BARCODE1
if [[ "$BARCODE2" =~ [a-z0-9] ]] ; then
play -q ./error.wav
else

echo "'$BARCODE1',$BARCODE2'" >> barcodes.csv
fi
fi

What's wrong? And is there a more optimal means of achieving this?

Upvotes: 0

Views: 131

Answers (1)

Aleks-Daniel Jakimenko-A.
Aleks-Daniel Jakimenko-A.

Reputation: 10653

Only numbers:

if ! [[ $BARCODE1 =~ ^[0-9]+$ ]]; then

Because of the + sign this is going to enter the if statement for empty strings as well. + means one or more times and * means zero or more time.

Two characters, numbers, two characters:

if ! [[ $BARCODE1 =~ ^[a-zA-Z][a-zA-Z][0-9]+[a-zA-Z][a-zA-Z]$ ]]; then

Once again, this is not going to match for strings like 'AABB'. If you think that 'AABB' is a valid barcode, then use this:

if ! [[ $BARCODE1 =~ ^[a-zA-Z][a-zA-Z][0-9]*[a-zA-Z][a-zA-Z]$ ]]; then

EDIT:

Also, if you know exact count of numbers in a barcode, then you could use {n}

if ! [[ $BARCODE1 =~ ^[a-zA-Z]{2}[0-9]{9}[a-zA-Z]{2}$ ]]; then

Which means 2 letters, 9 numbers, 2 letters

Upvotes: 7

Related Questions