Ubuntu – Convert multiline bash script to an one line

bashcommand linescripts

I have script like this:

for f in *
do
    #if condition
    if [[ -d $f ]]; then
        echo "$f is a directory";
    else
        echo "$f is not a directory";
    fi
done

Is it possible to convert multiple script into 1 line like this? (maybe I need to delete # comment statement(s)).

for f in *; do  if [[ -d $f ]]; then  echo "$f is a directory"; else  echo "$f is not a directory"; fi done

I can change for statement syntax in above script like:

  1. for f in *
  2. for f in *;
  3. for f in *;do

Same applies to if condition. In all the cases it should generate a proper 1 line. What could be the automated way to do this?

Best Answer

Parsing bash in oneliners is a hard task...

Anyway as a starting point, here goes a suggestion to cover very specific situations like the one presented

perl -p0e '
    s/#.*//; 
    s/;?\s+(do|done|then|else|fi)\s+/ ; $1 /g '