Modifying environment variables in the terminal is invalid for shell scripts

Environment variable validation problem

Verification process

Verify whether the shell script can obtain the latest environment variables in real time after the environment variables are modified.
1. Shell script
prints environment variables in a loop

#!/bin/bash  
  
for((i=1;i<=100;i++));  
do   
    echo "TEST_ENV: $TEST_ENV"
    sleep 5
done

2. Before executing the shell script, the environment variable TEST_ENV does not exist
. 3. Open terminal 1 and terminal 2, and terminal 1 executes the shell script in the background.

  • result:
    • Terminal 1: The script prints TEST_ENV as empty; echo prints TEST_ENV as empty
      User@3-WIN10BG0088 MINGW64 ~
      $ nohup ./test.sh &
      [1] 1133
      nohup: ignoring input and appending output to 'nohup.out'
      
      User@3-WIN10BG0088 MINGW64 ~
      $ cat nohup.out
      TEST_ENV:
      TEST_ENV:
      
    • Terminal 2: echo prints TEST_ENV as empty

4. Terminal 1: Set the environment variable TEST_ENV=create_env

  • result:
    • Terminal 1: The script prints TEST_ENV as empty; echo prints TEST_ENV as create_env
      User@3-WIN10BG0088 MINGW64 ~
      $ echo 'export TEST_ENV=create_env' >> ~/.bashrc && source ~/.bashrc
      
      User@3-WIN10BG0088 MINGW64 ~
      $ echo "$TEST_ENV"
      create_env
      
      User@3-WIN10BG0088 MINGW64 ~
      $ cat nohup.out
      TEST_ENV:
      TEST_ENV:
      TEST_ENV:
      TEST_ENV:
      TEST_ENV:
      TEST_ENV:
      TEST_ENV:
      TEST_ENV:
      
    • Terminal 2: echo prints TEST_ENV as empty

5. Newly open terminal 3

  • result:
    • Terminal 3: echo prints TEST_ENV as create_env
      User@3-WIN10BG0088 MINGW64 ~
      $ echo "$TEST_ENV"
      create_env
      

6. Terminal 1 modifies the environment variable TEST_ENV=update_env_1

  • result
    • Terminal 1: The script prints TEST_ENV as empty; echo prints TEST_ENV as update_env_1
    • Terminal 2: echo prints TEST_ENV as empty
    • Terminal 3: echo prints TEST_ENV as create_env
    • New terminal 4: echo prints TEST_ENV as update_env_1

result

Modifying environment variables in the current terminal will only take effect on the current terminal and subsequent newly started terminals. In addition, it will not take effect on shell programs that have been executed on the current terminal.

Guess you like

Origin blog.csdn.net/weixin_42492572/article/details/131431769