Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-05-13· OpenAIAi2 WildChat-4.8M (AI2)

In bash, if you source a script, and in that script you change the value of a variable,…

  1. User

    In bash, if you source a script, and in that script you change the value of a variable, will that variable have the same value in the main script?

  2. Assistant

    Yes, if you source a script in bash, any changes to variables made in that script will affect the variables in the parent shell (the shell from which you sourced the script). This is because sourcing a script with source scriptname or . scriptname executes the commands in the current shell environment, rather than in a subshell.

    Here's an example to illustrate this:

    Main Script (main.sh)

    #!/bin/bash
    
    # Define a variable
    myvar="Hello"
    
    # Print the value before sourcing
    echo "Before sourcing: $myvar"
    
    # Source the script
    source change_var.sh
    
    # Print the value after sourcing
    echo "After sourcing: $myvar"
    

    Sourced Script (change_var.sh)

    # Change the value of the variable
    myvar="World"
    

    When you run main.sh, it will produce the following output:

    Before sourcing: Hello
    After sourcing: World
    

    This demonstrates that the variable myvar in the main script (main.sh) was changed by sourcing change_var.sh.