Tech Support Forum banner

#include in bash shell script

72856 Views 2 Replies 3 Participants Last post by  konsolebox
Hi,

I was wondering whether there is an equivalent to the #include (used in c programs to import file content) in bash? If an equivalent doesn't exist then anyone know a workaround?
I have various files with defined paths and commands which I want to hack onto my .bashrc file at different times. I know I can just copy the text over to the .bashrc every time I need it, but it seems like a really dumb way to go about it.

Thanks in advance.
Status
Not open for further replies.
1 - 3 of 3 Posts
I was wondering whether there is an equivalent to the #include (used in c programs to import file content) in bash?
You can split up your scripts into files and "include" them with the source aka dot "." operator. The includes do not need to start with "#!/bin/bash", but they must either be in your PATH or have their PATH written exclusively in the main script.

Code:
#!/bin/bash

# A script that includes another script

source My_Other_Script.sh    # include is in $PATH
source /path/to/the/include/My_Other_Other_Script.sh   # explicit PATH
This thread is already old but I thought that some users might also want an answer if they see this so I made this post.

I was wondering whether there is an equivalent to the #include (used in c programs to import file content) in bash? If an equivalent doesn't exist then anyone know a workaround?
You can always use . or source for that but just in case you also want a function that only loads a script once even though it's already been called many times in many co-scripts (something similar to use of Perl, require of Ruby and include_once of PHP, you can use Shell Script Loader. It's a carefully planned framework for shell scripts that provides a function named include(). This function can accept complete paths or partial paths that will be completed using search paths just like the concept of binaries with $PATH. If you want you may optionally use an available compiler to compile the scripts to merge them into single large file.
1 - 3 of 3 Posts
Status
Not open for further replies.
Top