Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a file for variables using Bash?

I want to call a settings file for a variable. How can I do this in Bash?

The settings file will define the variables (for example, CONFIG.FILE):

production="liveschool_joe"
playschool="playschool_joe"

And the script will use these 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.?

like image 472
edumike Avatar asked Oct 11 '22 07:10

edumike


People also ask

How do you cite a file in shell script?

A file is sourced in two ways. One is either writting as source <fileName> or other is writting as . ./<filename> in the command line. When a file is sourced, the code lines are executed as if they were printed on the command line.

How do I reference an environment variable in bash?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.


2 Answers

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.

like image 283
Ezra Avatar answered Oct 13 '22 21:10

Ezra


Even shorter using the dot (sourcing):

#!/bin/bash
. CONFIG_FILE

sudo -u wwwrun svn up /srv/www/htdocs/$production
sudo -u wwwrun svn up /srv/www/htdocs/$playschool
like image 24
wnrph Avatar answered Oct 13 '22 21:10

wnrph