Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to strip comments from Bash script

Tags:

regex

bash

This is deceptively complex. I need a regular expression to strip comments from Bash shell scripts.

Bear in mind that $#, ${#foo}, string="this # string", string='that # string', ${foo#bar}, ${foo##baar}, and

string="really complex args=$# ${applejack##"jack"} $(echo "$#, again")"; `echo this is a ${#nasty[*]} example`

are all valid shell expressions that should not be stripped.

Edit: Note that:

# This is a comment in bash
  # But so is this
echo "foo bar" # This is also a comment

Edit: Note that lines that might be misconstrued as comments may be tucked inside HEREDOCs but since it is multi-line I can live without handling/accounting for it:

cat<<EOF>>out.txt
This is just a heredoc
# This line looks like a comment, but it isn't
EOF
like image 231
JeffG Avatar asked Jul 13 '11 14:07

JeffG


1 Answers

You cannot do that with regular expressions.

echo ${baz/${foo/${foo/#bar/foo}/bar}/qux}

You need to match nested braces. Regular expressions can't do that, unless you're willing to consider PCREs "regular expressions", in which case it would be simpler to just write the parser in Perl.

like image 69
n. 1.8e9-where's-my-share m. Avatar answered Sep 27 '22 20:09

n. 1.8e9-where's-my-share m.