
Dynamic Automation: Variables and User Input
Make your scripts intelligent and interactive. Master the use of User-Defined Variables, Environment Variables, and Command Substitution. Learn to ask users for information using the 'read' command.
Variables and Input: Creating Flexible Scripts
A script that only does one thing (like echo "Hello") isn't very helpful. To build powerful automation, your scripts need to handle data. They need to "Remember" information, perform calculations, and ask the user for directions.
In this lesson, we will move from "Static" scripts to "Dynamic" programs using Variables and the read command.
1. User-Defined Variables ADAD
In Bash, you define a variable by typing a name, an equals sign, and a value.
CRITICAL RULE: Do NOT put spaces around the = sign!
# Correct
NAME="Sudeep"
# Incorrect (Bash will try to run 'NAME' as a command)
NAME = "Sudeep"
Accessing the Value:
To use the variable, put a $ in front of its name.
echo "Hello $NAME"
2. Environment Variables ADAD
In addition to your own variables, Linux has a set of "Global" variables that every script can see.
$USER: Currently logged in user.$HOME: Path to the user's home directory.$PATH: List of folders the system searches for commands.$SHELL: The type of shell being used.
3. Command Substitution: Variables from the Shell
This is the most powerful feature of shell scripting. You can save the Output of a command into a variable.
# Syntax: VAR=$(command)
DISK_USAGE=$(df -h / | tail -1 | awk '{print $5}')
echo "Your disk is $DISK_USAGE full."
4. Arithmetic: Basic Math in Bash
Bash is a text-based language, so math requires a special syntax: $(( ... )).
NUM1=10
NUM2=5
SUM=$((NUM1 + NUM2))
echo "The total is: $SUM"
5. Getting Input: The 'read' Command
If you want your script to be "Interactive," use read.
#!/bin/bash
read -p "What is your project name? " PROJECT
read -sp "Enter your API secret key: " SECRET
echo -e "\nInitializing $PROJECT..."
-p: Prompt (shows a message).-s: Silent (hides the input—perfect for passwords).
6. Practical: The "Project Scaffolder" Script
Let's build a script that asks for a name and creates a standard project directory structure.
#!/bin/bash
read -p "Enter the project name: " PROJ_NAME
TARGET_DIR="$HOME/projects/$PROJ_NAME"
echo "Scaffolding project at $TARGET_DIR..."
# Create directories
mkdir -p "$TARGET_DIR/src"
mkdir -p "$TARGET_DIR/docs"
mkdir -p "$TARGET_DIR/tests"
# Create a starting file
touch "$TARGET_DIR/README.md"
echo "# $PROJ_NAME" > "$TARGET_DIR/README.md"
echo "Done! Type 'cd $TARGET_DIR' to begin."
7. Example: An Environment Variable Auditor (Python)
If you are a developer, you need to know which "Secrets" (API keys) are currently exposed in your shell. Here is a Python script that scans the system environment and flags variables that look like keys.
import os
import re
def audit_environment_variables():
"""
Scans os.environ for potentially sensitive data.
"""
sensitive_keywords = ["key", "secret", "password", "token", "auth"]
found = []
# os.environ is a dictionary of all shell variables
for key, value in os.environ.items():
if any(kw in key.lower() for kw in sensitive_keywords):
# Mask the value for safety
masked_value = value[:2] + "*" * (len(value) - 4) + value[-2:] if len(value) > 4 else "***"
found.append(f"{key}: {masked_value}")
return found
if __name__ == "__main__":
print("--- Environment Security Audit ---")
results = audit_environment_variables()
if results:
print(f"Detected {len(results)} sensitive-named variables:")
for r in results:
print(f" [!] {r}")
else:
print("No sensitive variables detected in current shell.")
8. Summary
Variables allow your script to "Think" and "Adapt."
- Assign with
NAME=VALUE(No spaces!). - Access with
$NAME. - Capture Output with
$(command). - Ask User with
read -p. - Protect Secrets with
read -s.
In the next lesson, we will learn how to make our scripts "Decide" things using Control Flow (If-Else Statements).
Quiz Questions
- Why does
NUM = 10fail in a Bash script? - How do you store the current date into a variable called
NOW? - Which system variable tells you the path to the current user's home folder?
Continue to Lesson 3: Control Flow—If-Else and Switch Case.