Say I have a bunch of files:


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

      echo "fooa" | bash

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

      echo "fooa" | bash

      echo "foob" | bash

      echo "fooc" | bash
      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?

  • 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


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"

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 .