Shell Variables in Linux

 

Shell Variables in Linux

Shell variables are placeholders for data, used to store and manage values dynamically during the execution of a shell session or script. Variables allow you to make your scripts more flexible and powerful.


Rules for Defining Shell Variables

  1. Variable Names:

    • Can contain letters, numbers, and underscores (_).
    • Must start with a letter or an underscore.
    • Cannot start with a number.
    • Variable names are case-sensitive (VAR is different from var).
  2. No Spaces Around =:

    • Do not add spaces before or after the = symbol.
    • Correct: name="Alice"
    • Incorrect: name = "Alice"
  3. Special Characters:

    • Avoid special characters in variable names.
    • Use only letters, numbers, and underscores.
  4. Quotes:

    • Enclose values in double quotes (") or single quotes (') if they contain spaces or special characters.
    • Double quotes allow variable interpolation, while single quotes treat the content literally.
      • "Hello $name": Expands $name.
      • 'Hello $name': Treats $name as plain text.
  5. No Keyword Usage:

    • Avoid using shell keywords or commands as variable names (e.g., if, for, while, etc.).
  6. Export for Environment Variables:

    • Use export to make a variable accessible to child processes.
    • Example: export PATH=$PATH:/new/path
  7. Read-Only Variables:

    • Mark variables as read-only using readonly.
    • Example: readonly pi=3.14

Types of Shell Variables

  1. Local Variables:

    • Exist only within the current shell session or script.
    • Defined using variable_name=value.
  2. Environment Variables:

    • Accessible across child processes or scripts.
    • Use export to define them.
    • Example: export LANG="en_US.UTF-8"
  3. Special Variables:

    • Predefined by the shell, they hold special meanings.
    • Examples:
      • $0: Name of the script.
      • $1, $2, ...: Positional parameters.
      • $?: Exit status of the last command.
      • $#: Number of arguments passed to the script.
  4. Readonly Variables:

    • Immutable once defined.
    • Example:

      readonly max_users=100 max_users=200 # Error: Cannot modify a readonly variable

How to Define, Access, and Manipulate Variables

  1. Defining Variables:


    name="Alice" age=25
  2. Accessing Variables:


    echo "Name: $name" echo "Age: $age"
  3. Reading Input into Variables:


    echo "Enter your favorite color:" read color echo "Your favorite color is $color."
  4. Unsetting Variables:


    unset name echo $name # Outputs nothing
  5. Default Values:

    • Use parameter expansion to set a default value if a variable is unset or empty.

    echo "Name: ${name:-Unknown}" # Outputs "Unknown" if $name is empty

Examples of Shell Variables

Example 1: Basic Usage

#!/bin/bash
name="Alice" echo "Hello, $name!"

Example 2: Read User Input


#!/bin/bash echo "Enter your name:" read user_name echo "Hello, $user_name!"

Example 3: Using Environment Variables


#!/bin/bash export MY_VAR="Environment Value" bash -c 'echo "MY_VAR in child process: $MY_VAR"'

Example 4: Using Special Variables


#!/bin/bash echo "Script Name: $0" echo "First Argument: $1" echo "Number of Arguments: $#"

Example 5: Read-Only Variables

#!/bin/bash
readonly app_version="1.0.0" echo "App Version: $app_version" # app_version="2.0.0" # This will cause an error

Best Practices

  1. Follow Naming Rules:

    • Use meaningful names, such as file_path, user_name, etc.
    • Avoid single-character names unless in loops (e.g., i, j).
  2. Use Quotes When Necessary:

    • Always quote variables to handle values with spaces or special characters.

    file_name="my file.txt" echo "File name: $file_name"
  3. Use unset to Free Variables:

    • Unset variables that are no longer needed to avoid conflicts.
  4. Export Variables Only When Needed:

    • Avoid exporting unnecessary variables to child processes.
  5. Document Constants with readonly:

    • Use readonly for values that should not be changed during script execution.

Conclusion

Shell variables are a powerful tool in scripting, providing the flexibility to store, manipulate, and share data. By adhering to naming rules, properly setting, unsetting, and accessing variables, you can write robust and efficient scripts to automate complex tasks.

Comments

Popular posts from this blog

IT Workshop GXESL208 KTU BTech 2024 Scheme - Dr Binu V P

Familiarization of basic Linux Commands- ls, mkdir, rmdir , rm, cat, cp, mv , chmod