0

I wrote a bash script tool, which contains main.sh, common.sh, config.sh. The main.sh used the commond source to load relative files.

I want to merge all files to single file for the convenience of distribution. Is there any best practice for that?

2
  • 1
    you can use your text editor, and replace the sourced files with the contents of the listed file or you can write a script that does it for you. Depends on how much/often you expect to do that. And this will be flagged as an "opinion" question, which are off topic here. Please read Help On-topic and Help How-to-ask before posting more Qs here. Good luck. Commented May 30, 2020 at 4:03
  • just rewrite your script and copy & paste everything in one single file? or you want to to something like 'head -n10 config.sh >> new.sh; head -n5 common.sh >> new.sh;' to get just some lines of each script? Commented May 30, 2020 at 5:54

2 Answers 2

4

Consider the following script from: Replacing 'source file' with its content, and expanding variables, in bash

It will "inline" the sourced file (referneced by '.' or by 'source' statement). It does not support calling source with parameters, locating files thru the PATH env var, etc. Hopefully, you do not need those features.

#!/usr/bin/env bash
while read line; do
    if [[ "$line" =~ (\.|source)\s+.+ ]]; then
        file="$(echo $line | cut -d' ' -f2)"
        echo "$(cat $file)"
    else
      echo "$line"
    fi
done < "$1"
Sign up to request clarification or add additional context in comments.

Comments

0

In your main.sh, replace source common.sh with the contents of common.sh and source config.sh with the contents of config.sh. When you use the command source, Bash executes the content of the file passed as argument in the current shell (as opposed to a subshell). So, removing the code from other files and moving them into main.sh will have the same effect.

Read more about source: https://ss64.com/bash/source.html

Relevant superuser question: https://superuser.com/questions/46139/what-does-source-do

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.