簡單的 bash 腳本不起作用

簡單的 bash 腳本不起作用

我對 bash 腳本還很陌生。我正在嘗試製作一個腳本來匯出 http_proxy 變數。這就是我在終端機上執行的操作:

$export http_proxy=http://proxy21.iitd.ernet.in:3128/
$export https_proxy=https://proxy21.iitd.ernet.in:3128/

這很好用。現在,這是我的腳本(稱為 setproxy):

#!/usr/bin/env bash
if [ $1 -eq 22 ]
then
    export http_proxy=http://proxy22.iitd.ernet.in:3128/
    export https_proxy=https://proxy22.iitd.ernet.in:3128/
elif [ $1 -eq 21 ]
then
    export http_proxy=http://proxy21.iitd.ernet.in:3128/
    export https_proxy=https://proxy21.iitd.ernet.in:3128/
elif [ $1 -eq 61 ]
then
    export http_proxy=http://proxy61.iitd.ernet.in:3128/
    export https_proxy=https://proxy61.iitd.ernet.in:3128/
elif [ $1 -eq 62 ]
then
    export http_proxy=http://proxy62.iitd.ernet.in:3128/
    export https_proxy=https://proxy62.iitd.ernet.in:3128/
fi

本質上,我想根據輸入設定適當的代理伺服器。我把它放在 bin 資料夾中,使其可執行,將 bin 新增到路徑中,登入和登出。終端機接受 setproxy 作為有效命令(至少沒有命令未找到錯誤)但是,當我這樣做時:

$setproxy 22

沒有效果。代理保持不變。我究竟做錯了什麼?

答案1

當您呼叫該腳本時,將會呼叫一個新的子 shell 來執行它。它的代理已設置,但父進程(您的 shell)的代理無法從子進程更改。嘗試採購腳本,即這樣稱呼它

. setproxy 21

然後該腳本將由您目前的 shell 解釋。

相關內容