Is there a way to split out sections of a script into a separate files and use something like an include statement to bring that code back into the main script where it is used when running it? The split out sections aren't stand alone code or modules, just related sections of code where I do different operations.

My script is getting rather long and hard to read. I tried using import but it looks like import will only work on a stand alone module or library. I've tried searching on everything I can think of for this but all of the google returns are about importing and loading libraries.


Thanks for the response but I see from your answer and re-reading my question,I left out one important detail. I'm referring to a Python program/script here.

  • If your Python code is strait line, functions may used to organize the code in different sections making it shorter and easier. See https://realpython.com/defining-your-own-python-function/ for more information.
    – bstipe
    Dec 11, 2023 at 1:21
  • Thanks bstip but that doesn't address the question. I understand functions. I just want to split those functions off to separate file so I don't have to scroll through all of those lines to get to the part of code I'm working on. Like a #include statement I've used in other languages.
    – Bam
    Dec 20, 2023 at 21:40

1 Answer 1


Yes - there is a way. It's a bit off-topic for RPi SE, but to save you the frustration of SO here's one way to do it:

Break your script into logically independent segments/files. Imagine a script file called bigblob.sh. Now, edit bigblob.sh by breaking it into 3 separate files that reflect a functional grouping: smallblob1.sh, smallblob2.sh, smallblob3.sh.

If smallblob1.sh is your "parent" script, and it is written in bash, you can insert smallblob2.sh and smallblob3.sh into it using the source command:

# Begin smallblob1.sh
do this, do that do something else

source smallblob2.sh 

do more stuff

source smallblob3.sh 

finish up

exit 0

Those are the basics. For details, there's a good blog article posted in Baeldung re use of the source command.

Your Answer

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

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