Linux - Shell Variables

Shell variables are placeholders used in Unix/Linux shells (like Bash, sh, or zsh) to store and manage data within a script or command-line session. They make shell scripts dynamic, flexible, and capable of handling different inputs and conditions. Variables can store values like text, numbers, commands, filenames, or even the output of other commands.


1. What Are Shell Variables?

Shell variables are named storage locations that hold information the shell can use. They work similarly to variables in programming languages but are simpler because shells treat everything as text.
Example:

NAME="Vidhisha"

Here, NAME is a shell variable holding a string.


2. Types of Shell Variables

Shell variables come in different categories based on their usage:

a) Local Variables

Defined and used within the current shell or script.

count=10

b) Environment Variables

These variables are available system-wide and can be passed to child processes. Common examples include:

  • PATH – Lists directories where the system looks for executables

  • HOME – User’s home directory

  • USER – Logged-in username

You can convert a local variable into an environment variable using export:

export NAME

c) Special Variables

These are built-in variables the shell provides. Examples:

  • $0 – Name of the script

  • $1, $2, … – Arguments passed to a script

  • $? – Exit status of the last command

  • $$ – Process ID of the current shell


3. Assigning and Accessing Variables

You assign variables without spaces:

file="report.txt"

To access their values, add a $ before the variable name:

echo $file

4. Using Variables in Shell Scripts

Variables help make scripts reusable.
Example:

#!/bin/bash
username="admin"
echo "Welcome, $username!"

5. Command Substitution

You can store the output of a command inside a variable:

today=$(date)

6. Default Values and Parameter Expansion

Shell supports advanced variable usage:

echo ${name:-"Guest"}   # Print default if variable is empty

In Summary

Shell variables are essential for scripting and command-line automation. They allow you to:

  • Store and reuse data

  • Pass information between commands

  • Handle user inputs dynamically

  • Make scripts flexible and powerful

 

Mastering shell variables is a fundamental step toward becoming efficient in Linux scripting and automation.