How to check if string begins with a square bracked in bash
bash
Solution
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
Problem
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.