0

Having a "library" with constants and functions (lib.sh), I can include it in my script (script.sh)

. /myfolder/lib.sh
......

Is there a way to merge the included file in the script (i.e. replace ./myfolder/lib.sh with the content of lib.sh)?

7
  • 1
    Why are you talking about bash in your title if the content refers to ksh?
    – roaima
    Jan 9 '17 at 14:31
  • Can be bash or ksh Jan 9 '17 at 14:35
  • 2
    cat /myfolder/lib.ksh >> script.ksh Jan 9 '17 at 14:35
  • 1
    do you want something specific to this case? (process script.sh and replace ". /myfolder/lib.sh" with the contents of lib.sh), or a more general solution that replaces any . or source command with the corresponding contents?
    – Jeff Schaller
    Jan 9 '17 at 14:51
1

Use sed:

sed -i.bak '\|^\. /myfolder/lib\.sh| {
    r /myfolder/lib.sh
    d
}' script.sh

What this script does is:

  • \|^\. /myfolder/lib\.sh| { ... } => locate lines that begin with . /myfolder/lib.sh and execute the commands inside the braces
  • r /myfolder/lib.sh => output the content of /myfolder/lib.sh
  • d => delete the line (. /myfolder/lib.sh)

The other lines are left as is of course.

0

untested: use GNU awk

gawk -i inplace '
    $1 == "." {system("cat " $2); next}
    {print}
' script.sh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.