Shell Scripting Variables


In shell scripting, variables are used to store and manipulate data. Shell scripts support several types of variables, including:

  1. User-Defined Variables:

    • These are variables that you define yourself to store data.
    • Variable names are case-sensitive and can consist of letters, numbers, and underscores. They must start with a letter or an underscore.
    • You can assign a value to a variable using the = operator without spaces around it.
    • Example:

      my_variable="Hello, World!"

  2. System Variables:

    • These are predefined variables that the shell uses for various purposes.
    • Common system variables include PATH, HOME, USER, SHELL, and PWD.
    • You can access their values using the $ symbol followed by the variable name.
    • Example:

      echo "My home directory is $HOME"

  3. Positional Parameters:

    • These variables are used to access command-line arguments passed to the script or function.
    • $0 represents the script's name, and $1, $2, etc., represent the first, second, and so on, arguments.
    • Example:

      echo "Script name: $0" echo "First argument: $1"

  4. Special Variables:

    • Shell scripting has several special variables with predefined meanings, such as $$ (current process ID), $? (exit status of the last command), and $# (number of arguments).
    • Example:

      echo "Process ID: $$"

  5. Array Variables:

    • Shell supports arrays, which are indexed collections of values.
    • You can declare an array and access its elements using square brackets [ ].
    • Example:

      my_array=("apple" "banana" "cherry") echo "First fruit: ${my_array[0]}"

  6. Read-Only Variables:

    • You can make a variable read-only using the readonly keyword. Once a variable is read-only, its value cannot be changed.
    • Example:

      readonly my_readonly_variable="This is read-only"

  7. Environment Variables:

    • Environment variables are global variables that are accessible to all processes.
    • You can set them using the export command.
    • Example:

      export MY_ENV_VAR="This is an environment variable"

  8. Local Variables (in Functions):

    • Variables declared within a function are local to that function and do not affect the global scope.
    • Example:

      my_function() {
        local local_var="This is a local variable"
        echo "$local_var"
      }

To use the value of a variable, you typically enclose its name in double quotes to ensure that any spaces or special characters are handled correctly. For example: "$my_variable".




Rs. 5.0 Rs. 10.0


Buy Now