Environment variables are dynamic values that affect the behavior of processes and programs on a computer system. In Bash, they play a crucial role in storing and managing information used by the shell and other applications.
Environment variables are name-value pairs that exist in a shell's environment. They store information such as system configuration, user preferences, and temporary data. These variables are accessible to the shell and any child processes it spawns.
To view all environment variables in your current Bash session, use the env
or printenv
command:
env
To view a specific environment variable, use the echo
command with the variable name prefixed by a dollar sign:
echo $HOME
You can set environment variables using the following syntax:
VARIABLE_NAME=value
For example, to set a custom path:
CUSTOM_PATH=/usr/local/bin:/usr/bin:/bin
echo $CUSTOM_PATH
To make an environment variable available to child processes, use the export
command:
export VARIABLE_NAME=value
This ensures that the variable is passed to any subshells or scripts that are executed.
PATH
: Specifies directories to search for executable filesHOME
: User's home directoryUSER
: Current user's usernameSHELL
: Path to the current shellPWD
: Current working directoryTo make environment variables persistent across sessions, add them to your shell's configuration file. For Bash, this is typically ~/.bashrc
or ~/.bash_profile
:
echo 'export CUSTOM_VAR="my value"' >> ~/.bashrc
source ~/.bashrc
Environment variables are commonly used in Bash scripts to make them more flexible and portable. Here's an example:
#!/bin/bash
echo "Hello, $USER!"
echo "Your home directory is: $HOME"
echo "Your current shell is: $SHELL"
Understanding and effectively using environment variables is crucial for efficient Bash command-line interface usage and script development. They provide a powerful way to customize your shell environment and pass information between processes.