In Linux shell scripting, assigning values to variables is a fundamental concept. Shell variables can hold strings, numbers, or command outputs, and their assignment follows specific rules and conventions.
1. Basic Syntax
The general syntax for assigning a value to a shell variable is:
variable_name=value
Key Points:
- No spaces are allowed around the = sign.
- Variable names can contain letters, numbers, and underscores but must start with a letter or underscore.
- Example:
name=John
age=30
2. Assigning String Values
Strings can be assigned directly without quotes unless they contain spaces or special characters.
- Without Spaces:
greeting=Hello
- With Spaces or Special Characters: Use single or double quotes:
message=”Hello, World!”
file_path=’/usr/local/bin’
3. Assigning Numeric Values
Numeric values are treated as strings unless used in arithmetic operations.
num=42
For arithmetic operations:
result=$((num + 8))
4. Assigning Values Using Command Substitution
The output of a command can be assigned to a variable using command substitution.
- Using Backticks (“):
current_date=`date`
- Using $() (preferred):
current_date=$(date)
Example:
user=$(whoami)
directory=$(pwd)
5. Assigning Environment Variables
Environment variables are global and can be accessed by child processes. They are created using the export command.
export ENV_VAR=”This is an environment variable”
6. Assigning Default Values
You can assign default values to variables using parameter expansion:
variable=${variable:-default_value}
If the variable is unset or empty, it will take the default value.
Example:
echo ${name:-Guest} # Outputs “Guest” if ‘name’ is unset.
7. Assigning Values from User Input
You can prompt the user for input and assign the input to a variable using read.
echo “Enter your name:”
read user_name
echo “Hello, $user_name!”
8. Assigning Values Conditionally
Variables can be assigned values based on conditions in scripts.
if [ -z “$name” ]; then
name=”Default Name”
fi
9. Examples
Example 1: Assigning Static Values
#!/bin/bash
name=”Alice”
age=25
echo “Name: $name”
echo “Age: $age”
Example 2: Assigning Command Output
#!/bin/bash
current_time=$(date)
echo “Current Time: $current_time”
Example 3: Using Default Value
#!/bin/bash
username=${USER:-unknown}
echo “User: $username”
Best Practices
- Use meaningful and descriptive variable names.
- Quote strings to avoid unexpected behavior with spaces or special characters.
- Prefer $() for command substitution.
- Avoid overwriting important system variables unless necessary.
- Use uppercase naming conventions for environment variables (e.g., CONFIG_PATH).
By understanding these concepts, you can effectively manage variables in your shell scripts to automate and streamline tasks.