Bash Script 12: Includes

Including passwords and keys in your script is bad for many reasons, security being number 1. All of these should be stored in another file, preferably a hidden file, that will never make it into your source control. That is just a universal no-no. Luckily, you can include another file’s contents into your script.

Include Variables

Including a file with variables for passwords and keys is the way to go:

#!/bin/bash

source .env

echo "Password in .env file is $PASSWORD"

Here, it just pulls in the entire file ‘.env’. For this file, just create some bash variables and those will be available after the source command in your script. Here’s an example:

PASSWORD="mySuperSecretPassWord111"

You do need to escape normal characters here, just like defining a variable in your script.

Include Functions

Your include can also have functions defined in it.

# functions.sh include file

# Grab the local ip address
getLocalIp() {
  IP=`ifconfig | \
      grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | \
      grep -Eo '([0-9]*\.){3}[0-9]*' | \
      grep -v '127.0.0' | \
      head -n1`
  echo $IP
}

Shorthand way to include a file

There’s a quicker way to include a file, by replacing source with a period. Here’s the example above updated to use this method:

#!/bin/bash

. .env

echo "Password in .env file is $PASSWORD"