PHP命令行基础与优势
PHP具备与Java、Perl及Python类似的执行能力,若早期了解此特性,或许能减少对其他语言的依赖学习成本。
过去学习Java往往是为了将程序部署在服务器上持续运行,实际上PHP同样可以实现这一需求。
php -h
Usage: php [options] [-f] [--] [args...]
php [options] -r [--] [args...]
php [options] [-B ] -R [-E ] [--] [args...]
php [options] [-B ] -F [-E ] [--] [args...]
php [options] -S : [-t docroot] [router]
php [options] -- [args...]
php [options] -a
-a Run as interactive shell
-c | Look for php.ini file in this directory
-n No configuration (ini) files will be used
-d foo[=bar] Define INI entry foo with value 'bar'
-e Generate extended information for debugger/profiler
-f Parse and execute .
-h This help
-i PHP information
-l Syntax check only (lint)
-m Show compiled in modules
-r Run PHP without using script tags <?..?>
-B Run PHP before processing input lines
-R Run PHP for every input line
-F Parse and execute for every input line
-E Run PHP after processing all input lines
-H Hide any passed arguments from external tools.
-S : Run with built-in web server.
-t Specify document root for built-in web server.
-s Output HTML syntax highlighted source.
-v Version number
-w Output source with stripped comments and whitespace.
-z Load Zend extension .
args... Arguments passed to script. Use -- args when first argument
starts with - or script is read from stdin
--ini Show configuration file names
--rf Show information about function .
--rc Show information about class .
--re Show information about extension .
--rz Show information about Zend extension .
--ri Show configuration for extension .
使用PHP命令行工具直接执行脚本,例如通过路径/usr/bin/php调用test.php文件。
命令缩写形式为 php test.php
即执行 test.php 脚本。
<?php
for($i=0;$i<10;$i++){
echo $i;
echo '\n';
}
?>
在脚本首行添加 #!/usr/bin/php 声明解释器,随后通过 chmod a+x 赋予脚本执行权限,即可像普通命令一样直接运行 ./test.php。
#!/usr/bin/php
<?php
for($i=0;$i<10;$i++){
echo $i;
echo " java-er.com \n";
}
?>
测试脚本能否长时间稳定运行,观察其在执行一小时后是否出现异常挂起,目标是实现持久化运行的命令行任务。
#!/usr/bin/php
<?php
for($i=0;$i<360;$i++){
echo $i;
sleep(10);
echo " java-er.com \n";
}
?>
支持从外部传入参数以增强脚本灵活性。
#!/usr/bin/php
<?php
var_dump($argc); //返回参数总个数
var_dump($argv);
exit;
?>
./test.php
int(1)
array(1) {
[0]=>
string(10) "./test.php"
}
./test.php a java php
int(4)
array(4) {
[0]=>
string(10) "./test.php"
[1]=>
string(1) "a"
[2]=>
string(4) "java"
[3]=>
string(3) "php"
}
总结
上述内容为PHP命令行编写Shell脚本的详细实例,旨在提供实用参考。如有任何疑问欢迎留言,小编将及时回复,感谢对本站的支持!