Custom environment variables in Linux scripting allow you to store and retrieve specific information that your scripts may need. This tutorial will guide you through the process of creating, setting, and using custom environment variables in a Linux environment.
To create a custom environment variable, you can use the export
command in the terminal or within a script:
export MY_VARIABLE="Hello, World!"
Alternatively, you can set the variable directly within a script:
MY_VARIABLE="Hello, Pavankumar!"
Remember that variables set this way will only be available to the current shell session or the script in which they are set. To make them persist across sessions, consider adding the export statement to your shell profile file (e.g., .bashrc
, .bash_profile
, or .zshrc
).
To access the value of a custom environment variable, use the $
symbol followed by the variable name:
echo $MY_VARIABLE
This will print the value of MY_VARIABLE
.
Let's create a simple script that uses a custom environment variable:
#!/bin/bash
# Set a custom environment variable
export GREETING="Pavankumar"
# Access and use the variable
echo "$GREETING, $USER!"
This script sets a custom environment variable GREETING
and uses it to greet the user.
You can unset a custom environment variable using the unset
command:
unset MY_VARIABLE
This removes the variable from the environment.
You can check if a variable is set using conditional statements:
if [ -z "$MY_VARIABLE" ]; then
echo "MY_VARIABLE is not set."
else
echo "MY_VARIABLE is set to: $MY_VARIABLE"
fi
This script checks if MY_VARIABLE
is set and prints its value if it is.
Custom environment variables in Linux scripting provide a way to store and retrieve information within scripts and across shell sessions. Whether you need to pass configuration settings, control script behavior, or store temporary data, custom environment variables offer a flexible and powerful solution. Experiment with these variables to enhance the functionality and adaptability of your Linux scripts.