0

Say I have a bunch of files:

a.sh
b.sh
c.sh
...
z.sh

and each of those files has a function in it like so:

   a(){
      echo "fooa" | bash
    }

now, if I could get all the functions in one file, they would look like:

   a(){
      echo "fooa" | bash
   }

   b(){
      echo "foob" | bash
   }

   c(){
      echo "fooc" | bash
   }
    ...
   z(){
      echo "fooz" | bash
   }

the problem is that they are in fact in separate files. What I am looking to do is dynamically write them to one file, so that one file can be sourced, instead of source 10 or 20 files.

What is the best way to do this?

One thing I could do is just loop through the files and append their contents to the 1 file that I want to source. Is there another way that might work?

7
  • 2
    cat *.sh > all.sh? May 13, 2018 at 5:55
  • probably would work fine, any way to remove white space? May 13, 2018 at 6:12
  • 1
    What's wrong with sourcing ? Or placing them in a folder and then sourcing everything in that folder ? May 13, 2018 at 6:18
  • or creating another script that sources all of those files....
    – Jasen
    May 13, 2018 at 6:22
  • 2
    @AlexanderMills Removing whitespace would introduce syntax errors when the newlines are removed. Why are you piping to bash?
    – Kusalananda
    May 13, 2018 at 6:30

1 Answer 1

3

cat *.sh > all.sh would concatenate all the files to one. That's a bit unclean, in that *.sh will also match all.sh if it already exists, but the redirection will clear all.sh before cat runs here.

You could also just write one script to source all the others (call it includeall.sh):

for f in *.sh; do
    if [ "$f" != "includeall.sh" ]; then
        . "$f"
    fi
done

Then source that with . includeall.sh. The if is there to avoid re-including includeall itself. Though it might not be a bad idea to put the a.sh..z.sh scripts in a separate directory. That would make the directory structure cleaner, and make it harder to accidentally source any wrong scripts. for f in dir/*.sh; do . "$f"; done in that case.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .