/bin/sh starts with check in script

Ian Smith smithi at nimnet.asn.au
Fri Feb 12 17:53:34 UTC 2016


In freebsd-questions Digest, Vol 610, Issue 5, Message: 1
On Thu, 11 Feb 2016 15:29:22 +0100 Jan Henrik Sylvester <me at janh.de> wrote:
 > On 02/10/2016 13:58, Sergei G wrote:
 > > I came up with this solution to check if variable $line starts with a
 > > hash.  Basically I am checking if line is a comment in the configuration
 > > file.
 > > 
 > > #!/bin/sh
 > > if expr "${line}" : '#.*' > /dev/null; then
 > >   echo Ignoring comment line
 > > fi

expr(1) suggests preferring sh(1) for maths expressions and parsing :)

 > > I had to redirect to /dev/null, because expr prints a number to STDOUT. 
 > > Is there a better way to do this kind of string matching check in
 > > /bin/sh (not bash)?
 > 
 > [ "${line#\#}" != "$line" ] && echo comment
 > 
 > See the Parameter Expansion section of sh(1).

That looks like it ought to work, but does not here on stable/9; I don't 
think it honours the escaping when expecting a second '#' or other char?

After some playing, this also finds comment lines that have optional 
whitespace before the first '#', not pinning comments only to column 1, 
while ignoring comments after other text.  Not what everybody needs ..

[ ! "`echo ${line%%#*} | tr -d [:blank:]`" ] && echo comment

BUG|FEATURE: if $line is the null string it is taken to be a comment.  

cheers, Ian


More information about the freebsd-questions mailing list