help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Official bash minifier


From: Koichi Murase
Subject: Re: Official bash minifier
Date: Sun, 7 Feb 2021 10:28:53 +0800

2021年2月7日(日) 8:52 Peng Yu <pengyu.ut@gmail.com>:
> Is there a robust minifier that works most of the time without
> changing the behavior of the original bash script? Thanks.

Have you tried any of these minifiers you found by the Google search?
Do these minifiers all fail with your scripts?

I think the most robust way is to let Bash parse the file and print
the code by `eval "content(){$filecontent}"; declare -pf content'. I'm
not sure if there is already such a one. I attach an example to do
that (minify.sh). You can use it like `./minify.sh
ScriptFileToMinify'. This safely removes comments and empty lines in a
robust way such that e.g. here documents are not broken, but it adds
redundant indentation.

[ Note: I think there is still some cases that the above method can
break the script, e.g., scripts using aliases to change its syntactic
structure, but I don't think there are so many such scripts, and I
don't think any other minifiers can handle such scripts. ]

If you want to remove indentation also, I think you can patch Bash not
to indent the result of `declare -pf`:

----------

diff --git a/print_cmd.c b/print_cmd.c
index 3c8c2d8f..2cde982b 100644
--- a/print_cmd.c
+++ b/print_cmd.c
@@ -1446,14 +1446,7 @@ static void
 indent (amount)
      int amount;
 {
-  register int i;
-
-  RESIZE_MALLOCED_BUFFER (indentation_string, 0, amount, indentation_size, 16);
-
-  for (i = 0; amount > 0; amount--)
-    indentation_string[i++] = ' ';
-  indentation_string[i] = '\0';
-  cprintf ("%s", indentation_string);
+  (void) amount;
 }

 static void

----------

Then, run minify.sh with the patched Bash:

  $ bash-noindent minify.sh FileToMinify

where `bash-noindent' is the patched Bash. You can also play around
`print_cmd.c' to further reduce spaces by replacing `" && "' with
`"&&"', `" "' with `""`, etc.

--
Koichi

Attachment: minify.sh
Description: Text Data


reply via email to

[Prev in Thread] Current Thread [Next in Thread]