In Linux shell scripting, variables are used to store information that can be accessed and manipulated within scripts or directly in the command line. Shell variables are a fundamental concept in shell scripting, enabling automation and dynamic behavior. Below is a detailed discussion of variables in the shell:
1. Defining Variables
Variables in shell scripts are created by assigning a value to a name.
variable_name=value
- No spaces should be present around the = sign.
- Example:
name=”John”
age=25
2. Accessing Variables
Variables are accessed by prefixing the variable name with a $.
echo $variable_name
- Example:
echo $name
3. Types of Variables
a) Local Variables
- These are defined in the current shell session and are not available to child processes.
- Example:
local_var=”This is local”
b) Environment Variables
- These are global variables that are passed to child processes.
- Created using the export command:
export ENV_VAR=”This is global”
c) Shell Variables
- Special variables maintained by the shell, such as $HOME, $PATH, $USER, etc.
4. Default Shell Variables
The shell provides several pre-defined variables:
- $HOME – User’s home directory.
- $PATH – Directories for executable commands.
- $USER – Current logged-in username.
- $PWD – Present working directory.
- $? – Exit status of the last command.
- $# – Number of arguments supplied to a script.
- $@ – All arguments as separate words.
- $* – All arguments as a single word.
5. Special Variable Operations
a) Command Substitution
Assign the output of a command to a variable:
current_date=$(date)
b) Arithmetic Operations
Use $((…)) for integer arithmetic:
a=10
b=20
sum=$((a + b))
echo $sum
c) String Manipulation
- Concatenate strings:
full_name=”$name Smith”
- Find string length:
echo ${#name}
d) Parameter Expansion
- Default values:
echo ${var:-“default_value”}
6. Best Practices
- Use meaningful variable names for clarity.
- Quote variables to prevent word splitting:
echo “$variable”
- Avoid overriding system variables unless necessary.
7. Example Script
#!/bin/bash
# Define variables
name=”Alice”
age=30
# Print variables
echo “Name: $name”
echo “Age: $age”
# Using environment variables
export GREETING=”Hello, World”
echo $GREETING
# Arithmetic operations
num1=5
num2=10
sum=$((num1 + num2))
echo “Sum: $sum”
8. Variable Scope
- Global Scope: Variables are accessible throughout the script or session.
- Local Scope: Use the local keyword inside functions to limit scope.
Summary
Shell variables are versatile tools for managing data in scripts. Understanding their types, usage, and best practices ensures efficient and maintainable scripting in Linux environments.