Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if string begins with a square bracked in bash

Tags:

bash

I need to go through my ini file and check if the line begins with a bracket, to figure out that the new config has started. Is there a way of checking this in bash? I tried

line="[test]"

if [[ "$line" =~ [.* ]]; then
    echo "Got it!"
else
    echo "Nothing found"
fi

but it doesn't work for me. I presume that the bracket needs to be somehow escaped, but I can't find any info as to how. Any help will be much appreciated.

like image 623
Kasia Gogolek Avatar asked Jan 18 '26 12:01

Kasia Gogolek


1 Answers

To do this, you should backslash the special character [, so :

line='[test]'

if [[ $line =~ ^\[ ]]; then
    echo "Got it!"
else
    echo "Nothing found"
fi

EXPLANATIONS

  • [ is the starting character to opening a REGEX class, like [0-9]
  • quotes are needed everywhere but not inside bash [[ ]] tests
like image 58
Gilles Quenot Avatar answered Jan 21 '26 07:01

Gilles Quenot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!