Deep Analysis and Solutions for "unary operator expected" Error in Bash Scripts

Nov 10, 2025 · Programming · 16 views · 7.8

Keywords: Bash scripting | conditional statements | unary operator expected | variable quoting | double bracket syntax

Abstract: This article provides an in-depth analysis of the common "unary operator expected" error in Bash scripting, explaining the root causes from syntactic principles, comparing the differences between single bracket [ ] and double bracket [[ ]] conditional expressions, and demonstrating three effective solutions through complete code examples: variable quoting, double bracket syntax, and set command usage.

Error Phenomenon and Root Causes

During Bash script development, programmers frequently encounter the "unary operator expected" error, which typically occurs in conditional statements. From the provided Q&A data, the error manifests in code like:

if [ $aug1 = "add" ]; then

When the variable $aug1 is undefined or empty, the Bash interpreter actually executes:

if [ = "add" ]; then

This syntactic structure is invalid in Bash because the equality operator requires two operands, but only one operand "add" is present, causing the interpreter to report an error.

Syntax Differences Between Single and Double Brackets

Bash provides two types of conditional expression syntax: traditional single brackets [ ] and extended double brackets [[ ]]. These two syntaxes exhibit significant differences in variable handling and functional features.

Single brackets [ ] are POSIX-standard compatible syntax that perform word splitting and pathname expansion on variables:

# Risky approach
if [ $variable = "value" ]; then
    echo "Match found"
fi

Double brackets [[ ]] are Bash extension syntax that do not perform word splitting:

# Safer approach
if [[ $variable == "value" ]]; then
    echo "Match found"
fi

Solution 1: Proper Variable Quoting

The most fundamental solution is to properly quote variables when using single bracket syntax:

# Correct variable quoting approach
if [ "$aug1" = "add" ]; then
    echo "Man Page for: add"
    echo ""
    echo "Syntax: add [number 1] [number 2]"
    echo ""
    echo "Description:"
    echo "Add two different numbers together."
    echo ""
    echo "Info:"
    echo "Added in v1.0"
    echo ""
elif [ -z "$aug1" ]; then
    echo "Please specify a command to read the man page."
else
    echo "There is no manual page for that command."
fi

By wrapping variables in double quotes, the conditional expression maintains correct syntax even when variables are empty:

# Actual execution when variable is empty
if [ "" = "add" ]; then  # Correct syntax
if [ = "add" ]; then      # Incorrect syntax

Solution 2: Using Double Bracket Syntax

For Bash-specific scripts, using double bracket syntax is recommended as it provides more powerful features and better safety:

# Safe approach using double brackets
if [[ $aug1 == "add" ]]; then
    echo "Displaying manual page for add command"
    # Display help information
elif [[ -z $aug1 ]]; then
    echo "Error: No command specified for manual page"
else
    echo "Error: No manual page available for '$aug1'"
fi

Advantages of double bracket syntax include:

Solution 3: Using set Command for Strict Checking

For scripts requiring higher security, use the set -u command at the beginning to enable undefined variable checking:

#!/bin/bash
set -u  # Enable undefined variable checking

# Script body
operation="man"
# aug1 variable is undefined

if [ "$aug1" = "add" ]; then
    echo "This line will never execute due to set -u"
fi

When the script attempts to use an undefined variable, set -u immediately reports an error and terminates execution, helping developers detect variable definition issues early.

Practical Application Scenarios

Consider a complete command-line tool script that needs to handle user input and parameter validation:

#!/bin/bash

# Method 1: Traditional single bracket syntax (requires careful quoting)
process_command_traditional() {
    local cmd=$1
    
    if [ "$cmd" = "install" ]; then
        echo "Starting installation process..."
    elif [ "$cmd" = "remove" ]; then
        echo "Starting removal process..."
    elif [ -z "$cmd" ]; then
        echo "Error: No command specified"
    else
        echo "Error: Unknown command '$cmd'"
    fi
}

# Method 2: Modern double bracket syntax (recommended)
process_command_modern() {
    local cmd=$1
    
    if [[ $cmd == "install" ]]; then
        echo "Starting installation process..."
    elif [[ $cmd == "remove" ]]; then
        echo "Starting removal process..."
    elif [[ -z $cmd ]]; then
        echo "Error: No command specified"
    else
        echo "Error: Unknown command '$cmd'"
    fi
}

# Test different scenarios
echo "Testing traditional method:"
process_command_traditional "install"
process_command_traditional ""

echo "Testing modern method:"
process_command_modern "install"
process_command_modern ""

Best Practices Summary

Based on the in-depth analysis of the "unary operator expected" error, we summarize the following best practices:

  1. Variable Quoting Principle: Always wrap variables in double quotes when using single bracket syntax
  2. Syntax Selection Strategy: Prefer double bracket syntax for Bash-specific scripts
  3. Defensive Programming: Use set -u for strict checking in critical script sections
  4. Code Readability: Maintain clarity and consistency in conditional expressions
  5. Error Handling: Provide reasonable default behavior for possible null or undefined variables

By following these practices, developers can significantly reduce conditional judgment errors in Bash scripts and improve code robustness and maintainability.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.