如何从一个bash脚本注释 [英] how to remove comments from a bash script

查看:113
本文介绍了如何从一个bash脚本注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做出越来越脚本文件作为参数的脚本。它应该从文件中删除和管道到另一个脚本注释。 (没有临时文件如果可能的话)

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?

推荐答案

下面是从脚本文件剥离注释的一个非常具体的bash路。它还剥离她邦线,如果有一个(毕竟,这是一个注释),并做了一些重新格式化:

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

该脚本转换为一个函数,并使用庆典内置声明来pretty -print所产生的功能(删除函数名,而不是周围的括号;更复杂的后处理可以删除它们,太,如果被判定有必要)

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).

在pretty印刷是在孩子做了庆典过程既避免与临时函数,并且由于子将有效地识别字符串污染的执行环境该变量作为函数的值。

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.

更新:

不幸的是,后shellshock以上不再起作用。然而,对于修补打击并可以击晕,下面可能确实

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.

这篇关于如何从一个bash脚本注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆