在 bash 中設置環境變量可以用 export 命令。當在命令行中執行時,只影響當前對話。若放到 ~/.bashrc,則該用戶每次打開 bash 都將有效。
如何通過 bash 腳本設置很多變量
#!/bin/bashexport HELLO=hello_worldecho $HELLO
執行該腳本,輸出:
hello_world
當此時在命令行中執行 echo $HELLO,發現 HELLO 變量爲空。
這是因爲腳本是在子 shell 中執行的,子 shell 退出時,變量即失效。
如何使腳本中的變量對當前 shell 生效呢?
可以使用 **source**指令。
運行 source -h查看幫助,可以發現 source 是在當前 shell 中執行腳本。
source evaluates the commands of the specified file in the current shell as a new block of code. This is different from starting a new process to perform the commands since the commands will be evaluated by the current shell, which means that changes in shell variables will affect the current shell.
