The practical implementation of shell programming A case study of php programs in multiple directories
This article mainly introduces the actual implementation of shell programming php program under multiple directories of the case study, has a certain reference value, friends in need can refer to. I hope you will learn a lot after reading this article. Next, let the editor take you to learn about it.
In a project I worked on last year, there was a need for php scripts in multiple directories to execute all php scripts in this directory.
To take this requirement, my consideration is to pass the directory as a parameter to the shell script instead of writing it in the program. Here is an additional point of knowledge: the predefined variables of the shell script
/ path/to/scriptname opt1 opt2 opt3 opt4 $0 $1 $2 $3 $4
$0 represents the script file name, $1 represents the first parameter, and so on. In addition, $# represents the number of parameters, and $* represents all parameters.
In my opinion, it is:
Shell script directory name 1 directory name 2...
It's easy to get all the directory names, just use $*. However, for the robustness of the program, we certainly need to check the directory name to see if the directory name has been entered and whether the directory exists.
# check whether the parameter if ($#
< 1));then echo 'please input some dirs' echo 'Usage ${0} dir1 dir2 ...' exit 1fi# 检查目录for dir in $*do if [ ! -d $dir ];then echo "$dir is not a dir" exit 2 fidone 首先,我们检查用户是否输入了参数,通过预定义变量$#来判断,$#如果小于1则表示没有输入参数。然后,进行目录的检测,查看输入的参数是否是一个目录。这里用[ ! -d $dir ] 来检测 。 验证性的代码完成后,接下来就是要执行目录下的php脚本了。其实主要的一点就是获取目录下的php文件名。一般的我们都以.php结尾的文件名作为php的脚本名。所以,这里我们只要执行以.php为后缀名的文件就行了。 # 执行目录下的php脚本for dir in $*do files=$(find $dir -name '*.php') for file in $files do $PHPBIN $file >/ dev/null 2 > & 1 donedone
Here we use a two-layer loop, with the outer loop traversing all the directories and the inner loop traversing all the php files under the directory.
Next, post the complete shell script
#! / bin/bash# executes the php script program PHPBIN=/usr/local/php/bin/phpif in multiple directories ($#
< 1));then echo 'please input some dirs' echo 'Usage ${0} dir1 dir2 ...' exit 1fi# 检查目录for dir in $*do if [ ! -d $dir ];then echo "$dir is not a dir" exit 2 fidone# 执行目录下的php脚本for dir in $*do files=$(find $dir -name '*.php') for file in $files do $PHPBIN $file >/ dev/null 2 > & 1 donedone
Finally, let's summarize what knowledge is used in the script:
Conditional judgment and circular execution
[- d file name] to detect whether the file is a directory
Find command to find files in the directory with the suffix .php
Predefined variables for shell programming
Thank you for reading this article carefully. I hope the editor will share the case studies of shell programming in many directories. At the same time, I also hope that you can support us, pay attention to the industry information channel, find problems and detailed solutions waiting for you to learn!