Techno Freak
Techno Freak

Reputation: 69

what is if [[ ! $1 =~ ^# ]]; in unix

I am reading a shell script in Unix. I have come upon the below line:

if [[ ! $1 =~ ^# ]];   

I understand the part which is on left side of equal sign but what does ~^# means.

Upvotes: 1

Views: 5740

Answers (2)

Emil L
Emil L

Reputation: 21111

According to http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression the =~ is:

<STRING> =~ <ERE> <STRING> is checked against the extended regular expression <ERE> - TRUE on a match

So the ^# is a extended regular expression. Since # is not a special character in extended regex. The meaning of the if checks that the string in $1 does not start with #. So on the command line

$ if [[ ! '#' =~ ^# ]]; then echo matches; else echo no match; fi
no match
$ if [[ ! 'b' =~ ^# ]]; then echo matches; else echo no match; fi
matches

Upvotes: 2

J. Chomel
J. Chomel

Reputation: 8395

  • The ~ allows to use POSIX regular expression matching ().
  • The ^ is a special character that evaluates the beginning of a line

In your case, ^# means a line beginning with #. Then your condition only takes care of lines that do not begin with #.

In shell scripting, lines beginning with # are comments, that are not evaluated as commands by the shell.

Upvotes: 1

Related Questions