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?

+2


source to share


3 answers


You can use sed inline with better regex:

sed -i.bak '/^[[:blank:]]*#/d "$1"

      



  • ^[[:blank:]]*#

    will #

    only match if preceded by additional spaces on each line
  • -i.bak

    the option will inline editing the input file using the .bak

    backup file extension in case something goes wrong.
+2


source


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.

+2


source


Yes, in general this type of problem can be solved without a temporary file.

This, however, will also depend on the complexity of the parsing required to determine when a comment delimiter character does not actually enter a comment.

0


source







All Articles