Print source code of bash script with its includes

Is there a way to view/show/print the source code of bash script with its includes (aka “sources”)?

For example:

sub.sh file

 function showMe(){
     echo "INCLUDE"
    }

main.sh file

#!/bin/bash    

source sub.sh

showMe    
echo "OK"

The “print” of main.sh will show:

#!/bin/bash    

showMe(){
 echo "INCLUDE"
}

showMe    
echo "OK"
Asked By: xlive

||
perl -p0e 'while(s/sources+(S+)/`cat $1`/e){}' foo.sh
Answered By: JJoao

You can try following awk:

awk '/^source/ { while (getline l <$2 > 0) print l; close($2); next; } { print; }' main.sh

so each line which starts with source fname should be replaced with contents of file if exists.

Answered By: taliezin

If you don’t mind executing the script too, here is a simple way to have the source code and its includes being displayed:

bash -v foo.sh
Answered By: jlliagre

Programs outputting their own source are called quines. There are a lot, although it is surprisingly non-intuitive to actually develop one. Most examples on the net does not include anything. A simple bash version can be found here:

#!/bin/bash
q=(
'#!/bin/bash'
'q=('
')'
'printf "%sn" "${q[@]:0:2}"'
'printf "47%s47n" "${q[@]}"'
'printf "%sn" "${q[@]:2}"'
)
printf "%sn" "${q[@]:0:2}"
printf "47%s47n" "${q[@]}"
printf "%sn" "${q[@]:2}"

There are quines in practially all programming languages. There are also quine chains (outputting source code on another language, that source outputs the original). This quine is a 128 language long chain.

Answered By: peterh
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.