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.?
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.
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.
Use the source
command.
source
For example:
#!/usr/bin/env bash
production="liveschool_joe"
playschool="playschool_joe"
echo $playschool
#!/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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With