Storing a Command in a Variable in a Shell Script

In shell scripting, you can store a command in a variable to improve code organization and reusability. This technique allows you to define commands once and execute them multiple times throughout your script.

Basic Command Storage

The basic syntax for storing a command in a variable is

variable_name="command"

For example

current_date="date"
list_files="ls -la"

To execute the stored command, you need to use command substitution or eval

# Using eval (less secure)
eval $current_date

# Using command substitution (preferred)
$($current_date)

Storing Commands in Arrays

You can store multiple commands in an array using this syntax

array_name=("command1" "command2" "command3")

Example

commands=("ls -l" "pwd" "date")

Execute all commands using a loop

for cmd in "${commands[@]}"
do
  eval "$cmd"
done

Access specific commands by index

# Execute the second command (pwd)
eval "${commands[1]}"

Better Alternatives

Instead of storing commands in variables, consider these safer approaches

Using Functions

show_date() {
    date "+%Y-%m-%d %H:%M:%S"
}

list_detailed() {
    ls -la "$1"
}

# Execute functions
show_date
list_detailed "/home"

Using Command Substitution

# Store command output instead of command itself
current_time=$(date)
file_count=$(ls | wc -l)

echo "Current time: $current_time"
echo "Files in directory: $file_count"

Security Risks and Problems

Storing commands in variables introduces several security and reliability issues

Problem Description Solution
Code Injection Malicious code can be injected if input is not sanitized Use functions or validate input
Variable Expansion Variables may expand at unexpected times Use proper quoting and functions
Syntax Errors Commands with syntax errors cause script failures Test commands before storing
Security Risk Arbitrary code execution if not properly validated Avoid eval, use alternatives

Why Avoid Eval

The eval command poses additional risks

  • Security vulnerabilities Executes arbitrary code without validation

  • Performance impact Runtime parsing and interpretation overhead

  • Debugging difficulty Hard to trace exact commands being executed

  • Unexpected behavior Complex variable expansion can cause issues

Best Practices

  • Use functions instead of storing commands in variables

  • Use command substitution to store command output

  • Always validate and sanitize any dynamic content

  • Avoid eval whenever possible

  • Use proper quoting to prevent word splitting

Conclusion

While storing commands in variables is possible in shell scripts, it introduces security risks and maintenance challenges. Functions and command substitution provide safer, more maintainable alternatives. Always prioritize security and code clarity over convenience when designing shell scripts.

Updated on: 2026-03-17T09:01:38+05:30

758 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements