Skip to content

Instantly share code, notes, and snippets.

@geminixiang
Created August 17, 2024 16:36
Show Gist options
  • Save geminixiang/6a42e80253ad8b1e75db445e98c7a87b to your computer and use it in GitHub Desktop.
Save geminixiang/6a42e80253ad8b1e75db445e98c7a87b to your computer and use it in GitHub Desktop.
~/.config/fish/functions/loadenv.fish
# loadenv - 讀取環境變數並設置為全局變數
# 此函數會從指定的 `.env` 文件中讀取環境變數,並處理包含等號(=)的變數值
# Settings:
# $ add funtion to ~/.config/fish/functions/loadenv.fish
# Usage:
# $ loadenv .env
function loadenv
# 循環處理文件中每一行非空且不以 # 開頭的行
for i in (cat $argv | grep -e '[^[:space:]]' | grep -v '^#')
# 使用 sed 將第一個等號前後的內容分開
# 第一部分(等號前)是變數名
# 第二部分(等號後)是變數值
set arr (echo $i | sed 's/=/\n/')
# 將等號後的所有內容重新組合為一個字符串
# 並將其設置為全局變數
set -gx $arr[1] (string join '=' $arr[2..-1])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment