Imports in shell scripting

Imports in shell scripting

This post shows how to source (load) a Bash function from a local or remote source into the current shell.

In shell scripting, using the source command (also known as the dot “.” command) allows to read and execute commands from a script file, and load its content into memory. This makes all variables, functions, and aliases defined in that script file become available in the current shell session.

Load from a local file

Similar to importing libraries in other programming languages, you can organize your frequently used code in different files in your project directory and then load them as you need. See this example:

project/root

# Project directory tree

root
├── lib/
│   └── common.sh
├── var/
│   └── stuff.sh
└── main_script.sh

If you want to import a function from root/lib/common.sh to main_script.shjust source that file:

main_script.sh
#!/bin/bash
# *** main_script.sh ***
source lib/common.sh
# .
# .

Load from a remote file

To load script content into your current shell without downloading the remote file, you can curl the content of the script and redirect it to the source command. You can also do this step in your shell script:

Remote file content:

print_hello
#!/bin/bash
print_hello() {
  echo "This is the boring hello world message"
}
# You can use a dot `.` instead of `source` as well
# Use -s flag to silence curl's info messages
$ source <(curl -s https://raw.githubusercontent.com/shakir85/utils/main/print_hello)

After that, you can invoke the print_hello function from your current shell:

$ print_hello
This is the boring hello world message

Use cases

  • Set environment variables, import functions, or modify the current shell’s behavior using the contents of a remote script.
  • You do not want to persist the data of the remote script on the host or want to load functions or variables on the fly.
  • Organize your scripts and code reusability.