php解釋命令行的參數


php cli模式下,可以用$argc, $argv來讀取所有的參數以及個數,如:

ghostwu@ghostwu:~/php/php1/1$ cat go1
#!/usr/bin/php
<?php

    echo '參數個數:' . $argc . PHP_EOL;
    echo '打印參數:' . PHP_EOL;
    print_r( $argv ) . PHP_EOL;

給文件加上可執行權限:

ghostwu@ghostwu:~/php/php1/1$ ls -l
total 8
-rwxrwxr-x 1 ghostwu ghostwu 337 4月  22 09:15 go
-rw-rw-r-- 1 ghostwu ghostwu 126 4月  22 09:20 go1
ghostwu@ghostwu:~/php/php1/1$ chmod a+x go1
ghostwu@ghostwu:~/php/php1/1$ ls -l
total 8
-rwxrwxr-x 1 ghostwu ghostwu 337 4月  22 09:15 go
-rwxrwxr-x 1 ghostwu ghostwu 126 4月  22 09:20 go1
ghostwu@ghostwu:~/php/php1/1$ ./go1
參數個數:1
打印參數:
Array
(
    [0] => ./go1
)
ghostwu@ghostwu:~/php/php1/1$ ./go1 a b c
參數個數:4
打印參數:
Array
(
    [0] => ./go1
    [1] => a
    [2] => b
    [3] => c
)

如果想把go1這個文件,在操作系統任意目錄下,都能執行,我們需要添加環境變量,我在家目錄下面建立一個目錄mybin,用來放自己開發的命令

ghostwu@ghostwu:~/mybin$ tail -2 ~/.bashrc
fi
export PATH=~/mybin:$PATH
ghostwu@ghostwu:~/mybin$ pwd
/home/ghostwu/mybin
ghostwu@ghostwu:~/mybin$ 
ghostwu@ghostwu:~/mybin$ echo $PATH
/home/ghostwu/mybin:/home/ghostwu/bin:/home/ghostwu/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
ghostwu@ghostwu:~/mybin$ 

再次打印$PATH,已經加入進來了,這個時候把開發好的命令拷貝到 ~/mybin目錄下,  以后在系統的任意目錄都能執行go1

ghostwu@ghostwu:~/mybin$ cp ~/php/php1/1/go1 .
ghostwu@ghostwu:~/mybin$ ls -l
total 8
-rwxrwxr-x 1 ghostwu ghostwu 126 4月  22 09:44 go1
ghostwu@ghostwu:~/mybin$ go1
參數個數:1
打印參數:
Array
(
    [0] => /home/ghostwu/mybin/go1
)
ghostwu@ghostwu:~/mybin$ cd /
ghostwu@ghostwu:/$ go1
參數個數:1
打印參數:
Array
(
    [0] => /home/ghostwu/mybin/go1
)
ghostwu@ghostwu:/$ cd /tmp
ghostwu@ghostwu:/tmp$ go1
參數個數:1
打印參數:
Array
(
    [0] => /home/ghostwu/mybin/go1
)

在Linux命令行下,很多的命令,或者說軟件都有一個-v參數來顯示版本號,這個功能怎么做?

$res = '';
if( $argc >= 2 ) $argv[1] == '-v' && $res = 'go version is 1.0';
    echo $res . PHP_EOL;

是不是很簡單,3行代碼就搞定了

ghostwu@ghostwu:~/mybin$ go -v
go version is 1.0
ghostwu@ghostwu:~/mybin$ ls -l
total 8
-rwxrwxr-x 1 ghostwu ghostwu 336 4月  22 09:49 go
-rwxrwxr-x 1 ghostwu ghostwu 126 4月  22 09:44 go1
ghostwu@ghostwu:~/mybin$ 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM