I want to check the condition like below. Line should not starts with #
symbol:
if[ ! ["$Line" == "#*"] ]; then
But this is not working.
I want to check the condition like below. Line should not starts with #
symbol:
if[ ! ["$Line" == "#*"] ]; then
But this is not working.
There are many problems in your snippet, but basically the syntax [![...]]
is not valid, in the bash (and many other shells) [[
is a single command, which cannot be split by any other character.
You can negate equality operator instead:
if [[ "$LINE" != \#* ]]; then echo yes; fi
Take also closer look to spaces surrounding brackets.
Assuming that you have a string in the variable line
and you want to output the string yes
if it doesn't start with the character #
. In the examples below, I will also output no
when the condition is not met.
case $line in
"#"*) echo no
esac
The case
statement takes a variable and then any number of (globbing) patterns, and executes the code for the pattern that matches the value of the variable. In this case we try to match the pattern "#"*
(the #
has to be quoted as to not be taken as introducing a comment), and if it matches, an echo
statement is executed.
If there are more patterns, then the code for all but the last pattern has to be terminated by ;;
, as in
case $line in
"#"*) echo no ;;
*) echo yes
esac
... and the code for a pattern may be empty:
case $line in
"#"*) ;;
*) echo yes
esac
The bash
shell also does pattern matching with globs in [[ ... ]]
with the ==
operator:
if [[ $line != "#"* ]]; then
echo yes
else
echo no
fi
In bash
, you may also use regular expression matching with the =~
operator within [[ ... ]]
:
if ! [[ $line =~ ^# ]]; then
echo yes
else
echo no
fi
or
if [[ $line =~ ^[^#] ]]; then
echo yes
else
echo no
fi
If you're paring a file line by line, then the shell is not the right tool for that job. Instead you may want to use something like awk
:
awk '/^[^#]/ { print yes }' <inputfile
Related:
if [[ $COMMIT_MESSAGE != Merge remote-tracking branch* ]]; then echo yes; else echo no; fi
, where I had to put double quotes around text:if [[ $COMMIT_MESSAGE != "Merge remote-tracking branch"* ]]; then echo yes; else echo no; fi
. – gluttony Aug 25 '22 at 10:13