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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…