Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

how to remove comments from a bash script

I'm trying to make a script that is getting a script file as a param. It should remove comments from the file and pipe it to another script. (with no temp file if possible)

at the beginning I was thinkig of doing this

cut -d"#" -f1 $1 | ./script_name

but it also clears a part of lines which aren't comments, because there are a few commands which uses # in them (counting string chars for example).

is there a way of doing it without a temp file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's one very bash-specific way of stripping comments from a script file. It also strips the she-bang line, if there was one (after all, it's a comment), and does some reformatting:

tmp_="() {
$(<script_name)
}" bash -c 'declare -f tmp_' | tail -n+2

This converts the script into a function, and uses the bash built-in declare to pretty-print the resulting function (the tail removes the function name, but not the surrounding braces; a more complicated post-process could remove them, too, if that were judged necessary).

The pretty-printing is done in a child bash process both to avoid polluting the execution environment with the temporary function and because the subprocess will effectively recognize the string value of the variable as a function.

Update:

Sadly, post shellshock the above no longer works. However, for patched bashes, the following probably does:

env "BASH_FUNC_tmp_%%=() {
$(<script_name)
}" bash -c 'declare -f tmp_' | tail -n+2

Also, note that this method does not strip comments which are internal to command or process substitution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...