In a shell script, you can declare global variables by simply defining them outside of any functions. By default, variables declared in a script are global unless they are declared as local within a function. Here's how to declare global variables:
-
Declare the Variable: Assign a value to the variable at the top level of the script.
global_var="I am a global variable" -
Access the Global Variable: You can access this variable from anywhere in the script, including inside functions.
echo $global_var -
Example Script:
#!/bin/bash # Declare a global variable global_var="I am a global variable" # Function to access the global variable function print_global { echo $global_var } # Call the function print_global
In this example, global_var is accessible both in the main body of the script and within the print_global function.
