How to remove comments from bash script
I am trying to create a script that receives a script file as a parameter. It should remove comments from the file and pipe it to another script. (no temp file if possible)
at the beginning I thought about it
cut -d"#" -f1 $1 | ./script_name
but it also cleans up some of the lines that are not comments, because there are several commands that use # in them (for example, counting string characters).
Is there a way to do this without a temporary file?
source to share
Here's one very bash-specific way to remove comments from a script file. It also breaks the "she-bang" line, if any (it's a comment after all), and does some reformatting:
tmp_="() {
$(<script_name)
}" bash -c 'declare -f tmp_' | tail -n+2
This converts the script to a function and uses the bash
inline declare
to properly print the resulting function ( tail
removes the function name but not the surrounding curly braces; a complex post process could also remove them if deemed necessary).
A fairly printable version is done in the child process bash
to avoid polluting the runtime with a temporary function and because the subprocess effectively recognizes the string value of a variable as a function.
Update:
Unfortunately the post shellshock above doesn't work. However, for the revised changes, it is likely the following:
env "BASH_FUNC_tmp_%%=() {
$(<script_name)
}" bash -c 'declare -f tmp_' | tail -n+2
Also note that this method does not strip comments that are internal to the command or process replacement.
source to share