yiaca
yiaca

Reputation: 187

check if string start with some string and ending in a digit - sh script

I want to check if some variable is starting with some string (A-) and ending with digit in shell script.

My script (test.sh):

#!/bin/bash

VAR=A-1

if [[ $VAR =~ A-*[0-9 ] ]]; then
        echo "yes"
else
        echo "no"
fi

The error I get after running sh test.sh:

test.sh: 5: test.sh: [[: not found

I tried to change the concession to: if [ $VAR =~ A-*[0-9 ] ]; then and got this error: test.sh: 5: [: A-1: unexpected operator

Upvotes: 1

Views: 2396

Answers (4)

ashish_k
ashish_k

Reputation: 1581

The variables should always be quoted: VAR="A-1"

The issue in your code is with the space in the square brackets: [...] which you've defined in the regex: [0-9 ]. There shouldn't be any space within it.

The correct code to check if some variable is starting with A- and ending with digit should be :

#!/bin/bash

VAR="A-1"

if [[ "$VAR" =~ ^A-.*[0-9]$ ]]; then
        echo "yes"
else
        echo "no"
fi

Please note the double quotes around the variable VAR.

As per the OP's comments, it looks like sh is being used instead bash , as the regex matching operator : =~ doesn't work in sh and is bash specific.

Updated code using sh:

#!/bin/sh

VAR="A-1"

if echo "$VAR"| grep -Eq "^A-.*[0-9]$"
  then
    echo "Yes"
else
    echo "no"
fi

Upvotes: 2

tshiono
tshiono

Reputation: 22022

The regex to match a string which starts with A- and ends with a digit should be: ^A-.*[0-9]$ or more strictly ^A-.*[[:digit:]]$. Then please modify your scpipt as:

#!/bin/bash

VAR="A-1"

if [[ $VAR =~ ^A-.*[0-9]$ ]]; then
    echo "yes"
else
    echo "no"
fi

Then invoke it with bash test.sh, not with sh test.sh.

Upvotes: 1

Rachid K.
Rachid K.

Reputation: 5211

Try something like : ${VAR:${#VAR}-1:1}

Cf. https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html

[[ "${VAR:${#VAR}-1:1}" =~ [0-9] ]] && echo yes

Upvotes: 0

Brad Lanam
Brad Lanam

Reputation: 5723

sh test.sh does not use bash to run the script, it uses sh, which, depending on the system, may not have the same capabilities as bash.

You can use:

bash test.sh

Or:

chmod a+rx test.sh # one time only
./test.sh          # your script is set to use /bin/bash in the #! line.

Upvotes: 0

Related Questions