php解释命令行的参数
生活随笔
收集整理的這篇文章主要介紹了
php解释命令行的参数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
php cli模式下,可以用$argc, $argv來讀取所有的參數(shù)以及個數(shù),如:
ghostwu@ghostwu:~/php/php1/1$ cat go1 #!/usr/bin/php <?phpecho '參數(shù)個數(shù):' . $argc . PHP_EOL;echo '打印參數(shù):' . PHP_EOL;print_r( $argv ) . PHP_EOL;給文件加上可執(zhí)行權(quán)限:
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 參數(shù)個數(shù):1 打印參數(shù): Array ([0] => ./go1 ) ghostwu@ghostwu:~/php/php1/1$ ./go1 a b c 參數(shù)個數(shù):4 打印參數(shù): Array ([0] => ./go1[1] => a[2] => b[3] => c )如果想把go1這個文件,在操作系統(tǒng)任意目錄下,都能執(zhí)行,我們需要添加環(huán)境變量,我在家目錄下面建立一個目錄mybin,用來放自己開發(fā)的命令
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,已經(jīng)加入進來了,這個時候把開發(fā)好的命令拷貝到 ~/mybin目錄下,? 以后在系統(tǒng)的任意目錄都能執(zhí)行g(shù)o1
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 參數(shù)個數(shù):1 打印參數(shù): Array ([0] => /home/ghostwu/mybin/go1 ) ghostwu@ghostwu:~/mybin$ cd / ghostwu@ghostwu:/$ go1 參數(shù)個數(shù):1 打印參數(shù): Array ([0] => /home/ghostwu/mybin/go1 ) ghostwu@ghostwu:/$ cd /tmp ghostwu@ghostwu:/tmp$ go1 參數(shù)個數(shù):1 打印參數(shù): Array ([0] => /home/ghostwu/mybin/go1 )在Linux命令行下,很多的命令,或者說軟件都有一個-v參數(shù)來顯示版本號,這個功能怎么做?
$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$?
總結(jié)
以上是生活随笔為你收集整理的php解释命令行的参数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Oracle Grid Control
- 下一篇: 二维变长数组