在 Linux Mint terminal 使用 nano 建立了 wanip 檔案, 內容是
#!/bin/bash
curl https://api.ipify.org -o wanip.txt
系統一直回覆 command not found
但我已對 wanip 檔案執行了 chmod u+x wanip
在 terminal 執行 curl https://api.ipify.org -o wanip.txt 也沒問題, 抓到了 路由器的 wan ip address 並寫入了 wanip.txt
怎麼回事?
Unix Shell Script 和 Windows batch file 不一樣,一個是多人多工,一個是單人作業
Unix 執行 Shell script時,會fork一個新的子程序,子程序原則上不會繼承母程序的環境變數(簡單來說就是會再開一個新畫面;這個畫面與原來無關)
所以直接執行命令時,環境變數(如path)會被預先代入,正常!
但是Script執行時,環境變數(如path)就需要自己定義,尤其是丟入排程執行時
Un*x Shell Script 規定
1.第一行指定shell如
#! /bin/bash
( #號+驚嘆號+空白+完整路徑Shell) 那個空白很重要,一定要加
2.Script 權限要有x權限,如chmod u+rx get_wanip.sh
如不使用chmod, 使用 /bin/bash get_wanip.sh 也行
3.確認所有相關程序/檔案路徑,可以使用where指令收尋Path如
where bash
where curl
4. 可以使用"點"開頭來執行指令,強制Script不fork子程序,繼承環境變數並回寫環境變數如
. get_wanip.sh
記住: 丟排程時此法會產生很多困擾,不要使用
在 #! 後面加了空白還是錯誤
iadmin@LinuxMint:~/Desktop/bash$ ls
wanip
iadmin@LinuxMint:~/Desktop/bash$ cat wanip
#! /bin/bash
curl -s https://api.ipify.org -o wanip.txt
iadmin@LinuxMint:~/Desktop/bash$ curl -s https://api.ipify.org -o wanip.txt
iadmin@LinuxMint:~/Desktop/bash$ ls
wanip wanip.txt
iadmin@LinuxMint:~/Desktop/bash$ wanip
bash: wanip: command not found
iadmin@LinuxMint:~/Desktop/bash$ which bash
/bin/bash
iadmin@LinuxMint:~/Desktop/bash$ which curl
/usr/bin/curl
iadmin@LinuxMint:~/Desktop/bash$ ls -l wanip
-rwxrw-r-- 1 iadmin iadmin 56 May 2 08:39 wanip
先執行 source wanip
應該就可以先初步執行你的script
如果能執行那代表你檔案沒問題
接著可以用 echo $PATH 這個指令來確認一下你的bash路徑
正常只會有/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games
如果在上面沒有發現你的bash資料夾
代表你沒有將你自己建立的bash資料夾路徑加入bash才會每次都必須完整打出路徑以及加上.才能執行
接著你輸入下面這個指令
nano ~/.bash_profile
看看有沒有下面這些指令 如果沒有 就加上去然後Ctrl+S存檔 在Ctrl+X離開nano
export PATH=$PATH:$HOME/Desktop/bash/
if [ -f ~/.bashrc ];
then
. ~/.bashrc
fi
存檔重開機後
以後就能直接打指令不需要加上 source前綴了
內文搜尋

X