bash: how to check if a string starts with '#'?
If you additionally to the accepted answer want to allow whitespaces in front of the '#' you can use
if [[ $line =~ ^[[:space:]]*#.* ]]; then
echo "$line starts with #"
fi
With this
#Both lines
#are comments
Just use shell glob using ==
:
line='#foo'
[[ "$line" == "#"* ]] && echo "$line starts with #"
#foo starts with #
It is important to keep #
quoted to stop shell trying to interpret as comment.
No regular expression needed, a pattern is enough
if [[ $line = \#* ]] ; then
echo "$line starts with #"
fi
Or, you can use parameter expansion:
if [[ ${line:0:1} = \# ]] ; then
echo "$line starts with #"
fi