乐闻世界logo
搜索文章和话题

What is the difference between a local and global variable in a shell script?

1个答案

1

In Shell scripting, variables can be defined as either local or global, with the primary distinction being their scope—where variables can be accessed.

Global Variables

Global variables are defined in the script and can be accessed and modified at any point within the script, including inside functions. Once set, they retain their values for the duration of the script execution unless explicitly modified or deleted.

Example:

bash
#!/bin/bash global_var='I am a global variable' function print_var() { echo $global_var } print_var # Output: I am a global variable echo $global_var # Output: I am a global variable

Local Variables

Local variables are defined within a function and are only valid inside that function. After the function ends, the value of a local variable cannot be accessed or modified outside the function.

In Bash, local variables are typically declared using the local keyword.

Example:

bash
#!/bin/bash function my_function() { local local_var='I am a local variable' echo $local_var } my_function # Output: I am a local variable echo $local_var # No output, as the variable local_var is not visible outside the function

Summary of Differences

  1. Scope:

    • Global Variables: Can be accessed anywhere in the script.
    • Local Variables: Only accessible within the function where they are declared.
  2. Lifecycle:

    • Global Variables: From declaration until the script execution ends or is explicitly deleted.
    • Local Variables: From declaration until the function execution completes.

Using local variables helps avoid variable name conflicts between different functions and reduces the risk of unintentionally modifying the global state in the script. When writing complex scripts, properly utilizing local variables enhances code modularity and maintainability.

2024年8月14日 17:23 回复

你的答案