Sourcing bash and Bourne shell scripts

Software

I’ve seen a lot of interest in bash migrations since Shellshock; whether it be as a result of moving to FreeBSD or otherwise.

Security aside, there are plenty of uses of bash out there where a simple Bourne Shell (sh) script would suffice. It also greatly helps with portability; not everyone has bash/dash installed by default.

For a few of my own bash scripts, I had to relearn how to source the contents of one script, and all its associated variables, into another. For example:

#!/usr/local/bin/bash

WORD="Bird"
SANDWICH="Grilled cheese"
Github Gist

Then in your other bash script:

#!/usr/local/bin/bash

source ./first.sh
echo $WORD
Github Gist

This will print Bird.

The equivalent sh script is the innocuous dot. This is distinct from the dot used to denote the current working directory, as you can see here:

#!/bin/sh

. ./first.sh
echo $WORD
Github Gist

The word “source” has some nice syntactic sugar to it, but I’d advise sticking to using the dot. Besides, one wouldn’t be writing shell scripts if one were concerned with syntactic sugar.

Author bio and support

Me!

Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.