BASH - if else, regular expression, OR

My bash script should check if the user is entering two numbers. Each number must be preceded by a + or - sign. The first number should be four digits in length, and the second number should be five digits.

No matter what values ​​I entered, the output is always Fail

The command line operator to run the script:

 $me add +1234 -12345 

script:

 #!/bin/bash #Script name add if [ $1 != [\+\-][0-9][0-9][0-9][0-9] ] || [ $2 != [\+\-][0-9][0-9][0-9][0-9][0-9] ] then echo Fail else echo Success fi 
+4
source share
3 answers

POSIX ( [ ) style tests do not perform pattern matching at all. The != Operator is a string comparison. Tests of type ksh ( [[ )) perform pattern matching using string shell patterns using the == operator and matching ERE with =~ . (No !=~ , But we can DeMorganify)

 ! [[ $1 =~ [-+][[:digit:]]{4} && $2 =~ [-+][[:digit:]]{5} ]] 

To match patterns in POSIX sh, the only option is the case .

+3
source

I don’t think there is a way (I was wrong, there is a way ) to perform pattern matching using the if . case can be used for such things. Working example:

 #!/bin/bash #Script name add case $1 in [+-][0-9][0-9][0-9][0-9]) r1='success' ;; *) r1='fail' ;; esac case $2 in [+-][0-9][0-9][0-9][0-9][0-9]) r2='success' ;; *) r2='fail' ;; esac if [ $r1 = 'fail' ] || [ $r2 = 'fail' ] then echo Fail else echo Success fi 
+1
source

You need to use double brackets to enable advanced functions that are more like traditional programming languages. For example, instead of -a use || instead of -o and && . Double brackets are also required to complete the pattern (matching .

In addition, brackets should be used for the entire expression, and not for each subexpression separately, and should include || .

I would use a line like:

 if [[ $1 == [+-][0-9][0-9][0-9][0-9] && $2 == [+-][0-9][0-9][0-9][0-9][0-9] ]] then echo "success" else echo "fail" fi 

EDIT : using == instead of != (Why is it so negative?) And remove references to the regular expression (uses pattern matching).

+1
source

Source: https://habr.com/ru/post/1439568/


All Articles