How to export variables in bash script?

LinuxLinuxBeginner
Practice Now

Introduction

In the world of Linux shell scripting, understanding how to export variables is crucial for managing system environments and creating robust, flexible scripts. This tutorial will explore the fundamentals of variable export in bash, providing developers with practical insights into sharing and managing variables across different processes and script contexts.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/UserandGroupManagementGroup(["`User and Group Management`"]) linux/BasicSystemCommandsGroup -.-> linux/declare("`Variable Declaring`") linux/BasicSystemCommandsGroup -.-> linux/source("`Script Executing`") linux/UserandGroupManagementGroup -.-> linux/env("`Environment Managing`") linux/UserandGroupManagementGroup -.-> linux/set("`Shell Setting`") linux/UserandGroupManagementGroup -.-> linux/export("`Variable Exporting`") linux/UserandGroupManagementGroup -.-> linux/unset("`Variable Unsetting`") subgraph Lab Skills linux/declare -.-> lab-419712{{"`How to export variables in bash script?`"}} linux/source -.-> lab-419712{{"`How to export variables in bash script?`"}} linux/env -.-> lab-419712{{"`How to export variables in bash script?`"}} linux/set -.-> lab-419712{{"`How to export variables in bash script?`"}} linux/export -.-> lab-419712{{"`How to export variables in bash script?`"}} linux/unset -.-> lab-419712{{"`How to export variables in bash script?`"}} end

Bash Variable Basics

Understanding Variables in Bash

In Bash scripting, variables are fundamental storage units that hold data for later use. They can store different types of information, such as strings, numbers, and arrays.

Variable Naming Conventions

Bash variables follow specific naming rules:

  • Start with a letter or underscore
  • Contain letters, numbers, and underscores
  • Case-sensitive
## Valid variable names
name="LabEx"
_count=10
user_id=1000

## Invalid variable names
2number="invalid"
user-name="not-allowed"

Types of Variables

Local Variables

Local variables are accessible only within the script or function where they are defined.

function example() {
    local local_var="I am local"
    echo $local_var
}

Environment Variables

Environment variables are available system-wide and can be accessed by all processes.

## Displaying environment variables
echo $HOME
echo $USER

Variable Assignment

Simple Assignment

name="John Doe"
age=30

Command Substitution

current_date=$(date)
file_count=$(ls | wc -l)

Variable Reference

Referencing Variables

greeting="Hello"
echo $greeting  ## Outputs: Hello
echo "${greeting}, World!"  ## Outputs: Hello, World!

Default Values

## Provide default value if variable is unset
username=${USER:-"anonymous"}

Common Practices

Practice Description Example
Quoting Prevents word splitting name="John Doe"
Escaping Handles special characters path="\/home\/user"
Parameter Expansion Advanced variable manipulation ${variable:-default}

Best Practices

  • Always quote your variables to prevent unexpected behavior
  • Use meaningful and descriptive variable names
  • Be consistent with naming conventions

By understanding these basics, you'll have a solid foundation for working with variables in Bash scripting, preparing you for more advanced topics like variable exporting.

Exporting Variables

What is Variable Exporting?

Exporting variables makes them available to child processes and subshells, extending their scope beyond the current shell environment.

Basic Export Syntax

Using the export Command

## Syntax: export VARIABLE_NAME=value
export DEVELOPER_NAME="LabEx User"
export PROJECT_PATH="/home/user/projects"

Alternative Export Method

## Declare and then export
LANGUAGE="English"
export LANGUAGE

Scope of Exported Variables

graph TD A[Parent Shell] --> B[Child Process 1] A --> C[Child Process 2] A --> D[Subshell]

Checking Exported Variables

List All Exported Variables

## Display all exported variables
export

Verify Specific Variable

## Check if a variable is exported
export | grep DEVELOPER_NAME

Export Behavior Comparison

Scenario Local Variable Exported Variable
Current Shell Accessible Accessible
Child Processes Not Accessible Accessible
Subshells Not Accessible Accessible

Advanced Export Techniques

Conditional Export

## Export only if condition is met
[ -d "$HOME/projects" ] && export PROJECT_ROOT="$HOME/projects"

Temporary Export

## Export for single command execution
TEMP_VAR="test" command

Common Use Cases

  1. Configuration Management
  2. Script Portability
  3. Environment Configuration
  4. Cross-Process Communication

Best Practices

  • Use meaningful and descriptive variable names
  • Be cautious with sensitive information
  • Prefer local variables when global scope is unnecessary
  • Use export sparingly to maintain clean shell environment

Unsetting Exported Variables

## Remove an exported variable
unset DEVELOPER_NAME

By mastering variable exporting, you'll enhance your Bash scripting capabilities and create more flexible, modular scripts in your LabEx learning journey.

Practical Use Cases

Environment Configuration Management

Setting Development Environment

export JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"
export PATH="$JAVA_HOME/bin:$PATH"
export MAVEN_OPTS="-Xmx512m"

Python Virtual Environment

export VIRTUALENV_PATH="$HOME/.virtualenvs/myproject"
export PYTHONPATH="$VIRTUALENV_PATH/lib/python3.8/site-packages"

Scripting and Automation

Dynamic Script Configuration

export LOG_DIRECTORY="/var/log/LabEx"
export MAX_BACKUP_COUNT=5

backup_script() {
    mkdir -p "$LOG_DIRECTORY"
    ## Backup logic using exported variables
}

Cross-Process Communication

graph LR A[Parent Script] -->|Export Variables| B[Child Process] B -->|Read Exported Variables| C[Processing] C -->|Return Results| A

Sharing Configuration Between Scripts

## parent_script.sh
export DATABASE_HOST="localhost"
export DATABASE_PORT=5432

## child_script.sh
echo "Connecting to $DATABASE_HOST:$DATABASE_PORT"

Conditional Environment Setup

Development Mode Toggle

export DEBUG_MODE=${DEBUG_MODE:-false}

if [ "$DEBUG_MODE" = true ]; then
    export LOGGING_LEVEL="DEBUG"
else
    export LOGGING_LEVEL="INFO"
fi

Security and Access Control

User-Specific Configurations

export USER_ROLE=$(id -gn)
export ACCESS_LEVEL=$([[ "$USER_ROLE" == "admin" ]] && echo "full" || echo "limited")

Performance Monitoring

Resource Allocation

export MAX_MEMORY_LIMIT=$(($(free -m | awk '/^Mem:/{print $2}') * 70 / 100))
export CPU_CORES=$(nproc)

Practical Export Scenarios

Scenario Purpose Example
Path Management Extend system PATH export PATH=$PATH:/custom/bin
Version Control Set development versions export NODE_VERSION=14
Temporary Settings Modify behavior temporarily export LANG=en_US.UTF-8

Container and Cloud Deployment

Docker and Kubernetes Configuration

export CONTAINER_REGISTRY="docker.labex.io"
export DEPLOYMENT_NAMESPACE="development"

Best Practices for Practical Use

  1. Use descriptive variable names
  2. Provide default values
  3. Validate exported variables
  4. Document exported configurations
  5. Be mindful of security implications

By understanding these practical use cases, you'll leverage exported variables effectively in your LabEx projects and Linux development workflows.

Summary

Mastering variable export in Linux bash scripting empowers developers to create more dynamic and interconnected shell environments. By understanding the export command, variable scoping, and practical use cases, programmers can write more efficient and flexible scripts that effectively manage system configurations and data sharing between processes.

Other Linux Tutorials you may like