1

I have 2 values, project and tag. I need check if them are empty/null and if project has only characters (except '-') and if tag has only numbers (expect '.').

User actually invert the order of them, first need be project and after tag.

I try invert the regex of $project and $tag if user wrong the order... But nothing happens, no errors and code continue.

if [ -z $project ] || 
   [ -z $tag ] || 
   [[ $project =~ '/^[0-9]+(\.[0-9]+)*$/' ]] || 
   [[ $tag =~ '/^[A-Za-z]+(\-[A-Za-z]+)*$/' ]] ; then
  echo Project or tag wrong, please try again. &&
  echo Example: file.sh project-test 1.99.2
fi

This code no give me errors, but also not do what I need. What I'm doing wrong here?

---- update with answer

My syntax was wrong, now it's working fine (without quotes).

if [[ $project =~ ^[0-9]+(\.[0-9]+)*$ ]] && 
   [[ $tag =~ ^[A-Za-z]+(\-[A-Za-z]+)*$ ]] ; then
  echo Correct
else
  echo Project or tag wrong, please try again. &&
  echo Example: file.sh project-test 1.99.2
fi
0

1 Answer 1

1

only let it pass when everything all right
grep -cP uses perl compatible regex, and print the number of matched lines
combined with echo ,count limited to 0 or 1 only
i functioned them and replace 4 "not" condition with 2 "yes" condition

#!/bin/bash
function check_arg() {
project=$1
tag=$2
if [ `echo $project|grep -cP '^[-a-zA-z]+$'`  -eq 1 ] &&
   [ `echo $tag|grep -cP '^[\.0-9]+$'`  -eq 1 ] ;
   then
   echo all good $project $tag
else
    echo Example : file.sh project-test 1.99.2
fi

}

check_arg project-test 99.2
check_arg 1.99.2  project-test

output

all good project-test 99.2
Example : file.sh project-test 1.99.2


Sign up to request clarification or add additional context in comments.

5 Comments

I tried and get the error [: -eq: unary operator expected.
the error is telling nothing appears between [ and -eq , which i should have protected with quote and counting. could you update your post with your exact code piece
you put the ending ` at the wrong place, which should go right after single quote,
I try it and get the same error, but I also find an other way that working fine, thanks you.
good luck. quotes can easily messed up and more than one way to fix

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.