How to reference a file for variables using Bash?

edumike picture edumike · Mar 8, 2011 · Viewed 176.2k times · Source

I want to call a settings file for a variable, how can I do this in bash?

So the settings file will define the variables (eg: CONFIG.FILE) :

production="liveschool_joe"
playschool="playschool_joe"

And the script will use those variables in it

#!/bin/bash
production="/REFERENCE/TO/CONFIG.FILE"
playschool="/REFERENCE/TO/CONFIG.FILE"
sudo -u wwwrun svn up /srv/www/htdocs/$production
sudo -u wwwrun svn up /srv/www/htdocs/$playschool

How can I get bash to do something like that? Will I have to use awk/sed etc...?

Answer

Ezra picture Ezra · Mar 8, 2011

The short answer

Use the source command.


An example using source

For example:

config.sh

#!/usr/bin/env bash
production="liveschool_joe"
playschool="playschool_joe"
echo $playschool

script.sh

#!/usr/bin/env bash
source config.sh
echo $production

Note that the output from sh ./script.sh in this example is:

~$ sh ./script.sh 
playschool_joe
liveschool_joe

This is because the source command actually runs the program. Everything in config.sh is executed.


Another way

You could use the built-in export command and getting and setting "environment variables" can also accomplish this.

Running export and echo $ENV should be all you need to know about accessing variables. Accessing environment variables is done the same way as a local variable.

To set them, say:

export variable=value

at the command line. All scripts will be able to access this value.