Category: c

  • Master Positional Parameters in Shell Scripting : Mastering $1, $2, $#, $@ (2026)

    What Are Positional Parameters in Shell Scripting?

    Positional Parameters : Bash or shell scripting, positional parameters allow you to access arguments passed to a script or function. They are incredibly useful when you want to handle user inputs dynamically.

    Why Learn Positional Parameters?

    • πŸ“¦ Helps you write flexible scripts
    • πŸ§‘β€πŸ’» Makes your scripts accept inputs
    • πŸ” Supports automation and reusability
    • 🧩 Essential for system scripting and DevOps

    Key Positional Parameters Explained

    ParameterMeaning
    $1, $2, …First, second, etc., arguments
    $0Name of the script
    $#Total number of arguments
    $@All arguments as separate words
    $*All arguments as a single word
    "$@"Preserves spaces and treats arguments individually
    "$*"Merges all arguments into one string

    Basic Script Example

    #!/bin/bash
    
    echo "Script Name: $0"
    echo "First Argument: $1"
    echo "Second Argument: $2"
    echo "Total Arguments: $#"
    echo "All Arguments (separately): $@"
    echo "All Arguments (together): $*"

    Run the script like this:

    bash myscript.sh apple banana cherry
    

    Output:

    Script Name: myscript.sh
    First Argument: apple
    Second Argument: banana
    Total Arguments: 3
    All Arguments (separately): apple banana cherry
    All Arguments (together): apple banana cherry
    

    Using "${@}" vs "${*}"

    Let’s see the difference:

    Example Script:

    #!/bin/bash
    
    echo "Using \"\$@\":"
    for arg in "$@"; do
        echo "$arg"
    done
    
    echo "Using \"\$*\":"
    for arg in "$*"; do
        echo "$arg"
    done
    

    Run with:

    bash myscript.sh "hello world" "foo bar"
    

    Output:

    Using "$@":
    hello world
    foo bar
    
    Using "$*":
    hello
    world
    foo
    bar
    

    πŸ“Œ "$@" keeps the full argument structure. "$*" splits everything.

    Bonus: Accessing All Arguments with a Loop

    #!/bin/bash
    
    echo "You passed $# arguments."
    
    i=1
    for arg in "$@"; do
        echo "Argument $i: $arg"
        ((i++))
    done
    

    Best Practices

    • Always quote your parameters: "$1", "$@"
    • Use $# to validate inputs
    • Use loops with "$@" for safe iteration

    Real-world Use Case: Validate Arguments

    #!/bin/bash
    
    if [ "$#" -ne 2 ]; then
        echo "Usage: $0 <filename> <username>"
        exit 1
    fi
    
    echo "Creating file $1 for user $2..."
    

    5 Practical Examples Using Positional Parameters in Shell Scripts

    Example 1: Greeting Script with $1 and $2

    #!/bin/bash
    
    echo "Hello, $1!"
    echo "Welcome to $2."
    

    Run:

    bash greet.sh Nish India
    

    Output:

    Hello, Nish!
    Welcome to India.
    

    Example 2: Check If Arguments Are Passed Using $#

    #!/bin/bash
    
    if [ "$#" -lt 2 ]; then
      echo "❌ Error: At least 2 arguments required."
      echo "Usage: $0 <arg1> <arg2>"
      exit 1
    fi
    
    echo "You passed $#: $1 and $2"
    

    Run:

    bash check.sh first

    Output:

    ❌ Error: At least 2 arguments required.
    Usage: check.sh <arg1> <arg2>

    Example 3: Loop Through All Arguments Using $@

    #!/bin/bash
    
    echo "πŸ“¦ List of arguments:"
    for item in "$@"; do
      echo "- $item"
    done

    Run:

    bash list.sh Mango Banana Apple

    Output:

    πŸ“¦ List of arguments:
    - Mango
    - Banana
    - Apple

    Example 4: Sum Two Numbers Using Positional Parameters

    #!/bin/bash
    
    num1=$1
    num2=$2
    sum=$((num1 + num2))
    
    echo "The sum of $num1 and $num2 is: $sum"

    Run:

    bash sum.sh 5 15

    Output:

    The sum of 5 and 15 is: 20

    Example 5: Handle All Arguments as One String Using $*

    #!/bin/bash
    
    echo "🧡 All arguments as one string: $*"

    Run:

    bash all.sh "one two" "three four"

    Output:

    All arguments as one string: one two three four

    Summary Table

    SymbolWhat It DoesExample
    $1First argumentecho $1
    $2Second argumentecho $2
    $#Argument countecho $#
    $@All arguments (safe loop)for i in "$@"
    $*All arguments (single string)echo $*

    Conclusion

    Mastering positional parameters in shell scripting is essential for writing interactive, powerful, and reusable scripts. Always remember:

    • $1, $2, etc. β€” access specific inputs
    • $# β€” count of arguments
    • "$@" β€” iterate safely
    • Use "$*" when combining arguments into a single string

    Frequently Asked Questions (FAQ)

    Q1: What are positional parameters in shell scripting?

    Positional parameters are special variables in shell scripts that store command-line arguments passed to the script. For example, $1 is the first argument, $2 is the second, and so on.

    Q2: What does $0 mean in a shell script?

    $0 represents the name of the script itself. It’s often used in usage messages or logs to display which script is running.

    Q3: What is the difference between $@ and $*?

    • $@ treats each argument as a separate string, ideal for loops.
    • $* treats all arguments as one single string, often used in quotes.
      Example:
    for arg in "$@"; do echo "$arg"; done   # Handles each argument correctly
    for arg in "$*"; do echo "$arg"; done   # May split arguments incorrectly
    

    Q4: How do I check how many arguments were passed to the script?

    Use $# to get the number of arguments.

    echo "You passed $# arguments."

    Q5: Can I access more than 9 arguments like $10, $11, etc.?

    Yes, but use braces to avoid ambiguity.

    echo "Tenth argument: ${10}"

    Q6: How can I loop through all arguments in a script?

    for arg in "$@"; do
      echo "Argument: $arg"
    done
    

    This safely loops through all arguments with proper quoting.

    Q7: What happens if an argument is missing in $1, $2, etc.?

    It returns an empty string. Always validate input count using $# before accessing specific arguments.

    Q8: Are positional parameters only available in Bash?

    No, they’re available in all POSIX-compliant shells, including sh, Bash, Zsh, and Ksh.

    Q9: How can I print all arguments including the script name?

    echo "Script: $0"
    echo "Arguments: $@"

    Q10: Can I shift positional parameters inside a script?

    Yes! Use shift to move parameters leftward:

    shift
    echo "Now \$1 is: $1"

    You can also Visit other tutorials of Embedded Prep 

    Special thanks to @embedded-prep for contributing to this article on Embedded Prep

  • Master CPP Design Patterns Tutorial for Beginners 2026

    What Are Ccpp Design Patterns?

    CPP Design Patterns : Design patterns are proven solutions to common software design problems. They help developers write reusable, maintainable, and scalable code. Think of them as blueprints that guide how to structure your code in a way that solves recurring challenges.

    Why Learn Design Patterns in C++?

    C++ is widely used for system programming, game development, embedded systems, and real-time applications. Learning design patterns in C++ allows you to:

    • Write cleaner and more modular code
    • Improve collaboration in teams
    • Understand industry-level software design
    • Crack technical interviews easily

    Types of Design Patterns

    Design patterns are mainly divided into 3 categories:

    TypeDescription
    CreationalDeal with object creation
    StructuralFocus on object composition
    BehavioralHandle object interaction and communication

    Examples of Each:

    • Creational: Singleton, Factory Method
    • Structural: Adapter, Decorator
    • Behavioral: Observer, Strategy

    Real-World Analogy

    Imagine you’re building a house:

    • Creational Pattern is like choosing how you build rooms (standard floor plan or customized).
    • Structural Pattern is like how rooms are connected (walls, doors).
    • Behavioral Pattern is like how people in rooms communicate (talking, signaling).

    Tools You Need

    To follow this C++ design pattern tutorial series, you need:

    • A basic understanding of C++ syntax
    • An IDE like Code::Blocks, VS Code, or CLion
    • A compiler like g++

    C++ Design Patterns Table

    CategoryPattern NamePurpose
    CreationalSingletonEnsures a class has only one instance and provides a global access point.
    Factory MethodDefines an interface for creating an object, but lets subclasses alter the type.
    Abstract FactoryProvides an interface to create families of related objects.
    BuilderConstructs a complex object step by step.
    PrototypeCreates new objects by copying an existing one.
    StructuralAdapterConverts one interface into another expected by clients.
    BridgeSeparates abstraction from implementation so they can vary independently.
    CompositeComposes objects into tree structures to represent part-whole hierarchies.
    DecoratorDynamically adds behavior to objects.
    FacadeProvides a unified interface to a set of interfaces in a subsystem.
    FlyweightShares objects to support large numbers efficiently.
    ProxyProvides a surrogate or placeholder for another object.
    BehavioralObserverNotifies all dependent objects of any changes to another object.
    StrategyAllows selecting an algorithm at runtime.
    CommandEncapsulates a request as an object.
    StateAllows an object to change its behavior when its internal state changes.
    Template MethodDefines the program skeleton, letting subclasses fill in the steps.
    IteratorProvides a way to access elements of a collection sequentially.
    MediatorDefines an object that coordinates interaction between other objects.
    MementoCaptures and restores an object’s internal state.
    VisitorAdds operations to classes without modifying them.
    InterpreterInterprets sentences in a language using a defined grammar.
    Chain of ResponsibilityPasses a request through a chain of handlers.


    C++ Adding Two Numbers

    #include <iostream>
    
    class CalculatorSingleton {
    private:
        // Private constructor to prevent instantiation
        CalculatorSingleton() {}
    
        // Delete copy constructor and assignment operator
        CalculatorSingleton(const CalculatorSingleton&) = delete;
        CalculatorSingleton& operator=(const CalculatorSingleton&) = delete;
    
    public:
        // Public method to get the single instance
        static CalculatorSingleton& getInstance() {
            static CalculatorSingleton instance;
            return instance;
        }
    
        // Method to add two numbers
        int add(int a, int b) {
            return a + b;
        }
    };
    
    int main() {
        // Get the singleton instance
        CalculatorSingleton& calc = CalculatorSingleton::getInstance();
    
        // Add two numbers
        int result = calc.add(10, 20);
    
        // Print the result
        std::cout << "The sum is: " << result << std::endl;
    
        return 0;
    }
    

    πŸ” Output:

    The sum is: 30

    Frequently Asked Questions (FAQs)

    What are design patterns in C++?

    Design patterns in C++ are reusable solutions to common software design problems. They represent best practices used by experienced developers to solve recurring problems in software architecture and object-oriented design.

    Why should I learn design patterns in C++?

    Learning design patterns helps you:

    • Write clean, reusable, and maintainable code
    • Understand and apply industry-standard practices
    • Improve problem-solving and architecture design skills
    • Prepare for technical interviews and real-world development

    Is this tutorial suitable for complete beginners?

    Yes! This tutorial is specially designed for beginners. It explains design patterns in simple language, with easy-to-understand examples and real-world use cases in C++.

    What topics will be covered in this C++ design patterns series?

    The tutorial will cover:

    • Introduction to Design Patterns
    • Types of Design Patterns (Creational, Structural, Behavioral)
    • Step-by-step implementation of each pattern in C++
    • Best practices and use cases

    Do I need to be an expert in C++ to follow this tutorial?

    No. You just need to have a basic understanding of C++, such as classes, objects, inheritance, and functions. The tutorial is crafted for beginners and will guide you through each concept.

    Are there code examples and explanations for each pattern?

    Yes! Every design pattern in this series comes with:

    • Simple code examples in C++
    • Detailed explanations
    • Diagrams (where needed)
    • Real-world applications

    Will this help in job interviews?

    Absolutely. Many software engineering interviews include questions on design patterns. Understanding these concepts will give you a competitive edge during technical interviews.

    How can I practice these design patterns?

    Each tutorial includes:

    • Hands-on exercises
    • Code snippets you can run and modify
    • Mini-project ideas to build confidence

    Is this Master CPP Design tutorials free?

    Yes, the entire Cpp Design Patterns Tutorial for Beginners is free to read and follow. No sign-up or payment is required.

    You can also Visit other tutorials of Embedded Prep 

    Special thanks to @mr-raj for contributing to this article on Embedded Prep