0
0
Bash Scriptingscripting~5 mins

Configuration file reading in Bash Scripting

Choose your learning style9 modes available
Introduction
Reading configuration files lets your script use settings without changing the script itself. It helps keep things organized and easy to update.
You want to change script settings without editing the script code.
You have multiple scripts that share the same settings.
You want to keep sensitive info like passwords outside the script.
You want to make your script flexible for different environments.
You want to separate data from code for easier maintenance.
Syntax
Bash Scripting
source /path/to/config_file
# or
. /path/to/config_file
The config file should contain valid bash variable assignments, like VAR=value.
Use 'source' or '.' to load the config file into the current script environment.
Examples
Loads variables from 'myconfig.cfg' in the current directory.
Bash Scripting
source ./myconfig.cfg
Loads config from an absolute path using the dot command.
Bash Scripting
. /etc/myapp/config.cfg
Example content of a config file with two variables.
Bash Scripting
# Inside config file:
USERNAME=admin
PASSWORD=secret
Sample Program
This script reads database settings from 'app.config' and prints a connection message.
Bash Scripting
#!/bin/bash

# Load config file
source ./app.config

# Use variables from config
echo "Connecting to database at $DB_HOST with user $DB_USER"
OutputSuccess
Important Notes
Make sure the config file has no spaces around '=' in variable assignments.
Avoid running untrusted config files as they can execute any bash code.
Use quotes around variables when using them to avoid word splitting issues.
Summary
Use 'source' or '.' to read config files in bash scripts.
Config files hold variable assignments to keep scripts flexible.
Always check config file content for safety before sourcing.