Bash Script 12: Includes

Published On: Friday, November 16th 2018
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: [bash] #!/bin/bash source .env echo "Password in .env file is $PASSWORD" [/bash] 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: [bash] PASSWORD="mySuperSecretPassWord111" [/bash] 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. [bash] # 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 } [/bash]

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: [bash] #!/bin/bash . .env echo "Password in .env file is $PASSWORD" [/bash]

Tag Cloud

Copyright © 2026 Barry Gilbert.