在 Linux 伺服器上撰寫 PHP 自動化腳本時,每次輸入 php script.php 顯得繁瑣。實際上只需在檔案首行加入 Shebang 指定 PHP 解釋器路徑,並賦予執行權限,即可像 Shell 腳本一樣直接執行。
test_run.php:#!/usr/bin/php
Here is some plain text.
Here is the file name:
chmod u+x ./test_run.php
./test_run.php
# 輸出:
# Here is some plain text.
# Here is the file name:
# ./test_run.php

#!/usr/bin/php:Shebang 行,指定 PHP CLI 解釋器絕對路徑(可用 which php 確認)chmod u+x:賦予檔案擁有者執行權限$argv[0]:取得腳本檔案路徑(包含 ./ 前綴)$argv[1]、$argv[2]... 接收命令列參數PHP 官方文件:Command line usage - Example #2 Script intended to be run from command line
完成設定後,您可以將 PHP 腳本放入 /usr/local/bin 或加入 PATH 目錄,像系統指令一樣在任何路徑直接呼叫。