很有意思,写完之后能够提高开发效率。
总install.sh
#!/bin/bash
# Check if user is root
if [ $(id -u) != "0" ]; then
echo "Error: You must be root to run this script, please use root to install ant"
exit 1
fi
cur_dir=$(pwd)
# 引入配置
. conf/init.conf
# 引入公共函数
. init/main.sh
# 检查配置
Check_INITConf()
{
if [ ! -s "${cur_dir}/conf/init.conf" ]; then
Echo_Red "init.conf was not exsit!"
exit 1
fi
if [[ "${DOMAIN_NAME}" = "" || "${DB_NAME}" = "" || "${DB_USER}" = "" || "${DB_HOST}" = "" || "${DB_PWD}" = "" ]]; then
Echo_Red "Can‘t get values from init.conf!"
exit 1
fi
}
Check_INITConf
input_domain=${DOMAIN_NAME}
input_name=${DB_NAME}
# 修改hosts中
if [[ "${ENV}" = "local" ]]; then
. init/hosts.sh
fi
# nginx 初始化,父脚本中的变量会自动传入引入的脚本中
. init/nginx.sh
# 数据库初始化
. init/database.sh
# 项目初始化
. init/project.sh
# 小程序初始化
. init/taro.sh
echo "+------------------------------------------------------------------------+"
echo " Success!!! "
echo "+------------------------------------------------------------------------+"
echo " PHP is the best language in the world! "
echo "+------------------------------------------------------------------------+"
echo " Open Browser And Input URL: ${DOMAIN_NAME} "
echo "+------------------------------------------------------------------------+"
配置文件
## 基本信息 ##
APP_NAME=‘‘
DOMAIN_NAME=‘‘
## 数据库 ##
DB_HOST=‘‘
DB_NAME=‘‘
DB_USER=‘‘
DB_PWD=‘‘
## 环境 ## local online test
ENV=‘local‘
## 微信 ##
APP_ID=‘‘
APP_SECRET=‘‘
MCHID=‘‘
WEIXIN_PAY_KEY=‘‘
main.sh
Color_Text()
{
echo -e " \e[0;$2m$1\e[0m"
}
Echo_Red()
{
echo $(Color_Text "$1" "31")
}
Echo_Green()
{
echo $(Color_Text "$1" "32")
}
Echo_Yellow()
{
echo $(Color_Text "$1" "33")
}
Echo_Blue()
{
echo $(Color_Text "$1" "34")
}
hosts.sh
#!/bin/bash
# 判断hosts中有域名
input_domain=${DOMAIN_NAME}
if cat ‘/etc/hosts‘ | grep "$input_domain" > /dev/null #/dev/null 表示空设备文件
then
Echo_Green "======> hosts $input_domain is ok."
else
sed -i "1i\127.0.0.1 $input_domain" /etc/hosts
Echo_Green "======> hosts $input_domain add ok."
fi
nginx.sh
#!/bin/bash
# 生成nginx配置
# cur_dir=$(pwd)
# cur_dir=$(dirname $(pwd))
nginx_str="server\n
{\n
\t listen 80;\n
\t #listen [::]:80 default_server ipv6only=on;\n
\t server_name ${input_domain};\n
\t index index.html index.htm admin.php;\n
\t root ${cur_dir}/web-admin/Public;\n
\t #error_page 404 /404.html;\n
\t include enable-php-pathinfo.conf;\n
\t location /nginx_status\n
\t {\n
\t \tstub_status on;\n
\t \taccess_log off;\n
\t }\n
\t location / { \n
\t\t if (!-e \$request_filename) { \n
\t\t\t rewrite ^/$input_name/(.*)$ /api.php?s=\$1 last; \n
\t\t\t break; \n
\t\t\t rewrite ^(.*)$ /index.php?s=/\$1 last; \n
\t\t }\n
\t\t if (!-e \$request_filename) { \n
\t\t\t rewrite ^(.*)$ /admin.php?s=\$1 last; \n
\t\t } \n
\t } \n
\t location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$\n
\t {\n
\t \texpires 30d;\n
\t }\n
\t location ~ .*\.(js|css)?$\n
\t {\n
\t \texpires 12h;\n
\t }\n
\t location ~ /\.\n
\t {\n
\t \tdeny all;\n
\t }\n
\t access_log /home/wwwlogs/access.log;\n
}"
nginx_conf_file="/usr/local/nginx/conf/vhost/$input_name.conf"
if [ ! -f $nginx_conf_file ]; then
touch $nginx_conf_file
Echo_Green "======> nginx_conf $nginx_conf_file create ok."
fi
/bin/echo -e $nginx_str >$nginx_conf_file
Echo_Green "======> nginx_conf $nginx_conf_file has init ok. "
# 重启nginx
nginx -s reload
Echo_Green "======> nginx reload ok."
database.sh
#!/bin/bash
host=${DB_HOST}
dbname=${DB_NAME}
user=${DB_USER}
pwd=${DB_PWD}
# 只能通过单字母传参数
create_res=`php ${cur_dir}/init/createdb.php -h $host -u $user -p $pwd -d $dbname`
if [[ "$create_res" = 1 ]];
then
Echo_Green "======> create database $dbname ok."
else
Echo_Red "======> create database $dbname fail."
fi
# 初始化sql
php ${cur_dir}/init/sqlversion.php -h $host -u $user -p $pwd -d $dbname
createdb.php
<?php
header("Content-Type: text/html;charset=utf-8");
error_reporting(E_ALL | E_STRICT);
$param_arr = getopt(‘h:u:p:d:‘);
$host = $param_arr[‘h‘] ?: ‘127.0.0.1‘;
$user = $param_arr[‘u‘];
$pwd = $param_arr[‘p‘];
$dbname = $param_arr[‘d‘];
if (!$user || !$pwd || !$dbname) {
echo 2;
return;
}
// 创建数据库
try {
$conn = new PDO("mysql:host=$host", $user, $pwd);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE IF NOT EXISTS " . $dbname . " DEFAULT CHARSET utf8 COLLATE utf8_general_ci;";
// 使用 exec() ,因为没有结果返回
$conn->exec($sql);
echo 1;
$conn = null;
return;
} catch (PDOException $e) {
// echo $sql . "<br>" . $e->getMessage();
echo 0;
$conn = null;
return;
}
sqlversion.php
<?php
header("Content-Type: text/html;charset=utf-8");
error_reporting(E_ALL | E_STRICT);
$param_arr = getopt(‘h:u:p:d:‘);
$host = $param_arr[‘h‘] ?: ‘127.0.0.1‘;
$user = $param_arr[‘u‘];
$pwd = $param_arr[‘p‘];
$dbname = $param_arr[‘d‘];
// $create_db_sql = "CREATE DATABASE IF NOT EXISTS test_db CHARACTER SET utf8 COLLATE utf8_general_ci";
$lnk = new PDO(‘mysql:host=‘ . $host . ‘;dbname=‘ . $dbname . ‘‘, $user, $pwd);
$lnk->query(‘SET NAMES utf8‘);
global $a;
$is_ztver_exits = $lnk->query("show tables like ‘%ztver%‘");
$row = $is_ztver_exits->fetch();
if ($row) {
$maxver = getMaxVer($lnk);
} else {
$ztversql = "CREATE TABLE `ztver` (`ver` int(11) NOT NULL DEFAULT ‘0‘,`changelog` text NOT NULL,`dateline` int(11) unsigned NOT NULL,PRIMARY KEY (`ver`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=‘DB版本表‘;";
$dbresult = $lnk->query($ztversql);
$maxver = 0;
}
if (!$maxver) {
$maxver = 0;
}
$allweifilename = getWeiFilename($maxver, ‘sqlfile‘);
asort($allweifilename);
foreach ($allweifilename as $v) {
$a = populate_db($lnk, ‘‘, $v);
if ($a !== 1) {
break;
} else {
echo colorize("info: process version " . basename($v) . "... completed.\n","Green");
}
}
$lnk->query(‘END‘);
if ($a === 1) {
echo colorize("======> table updating complete.\n","Green");
} else {
if ($a) {
echo colorize("table err:" . $a[0][0][2] . "\n","Red");
} else {
echo colorize("======> table updating complete.\n","Green");
}
}
function getMaxVer($lnk)
{
$sql = "SELECT max(ver) FROM `ztver`";
$result = $lnk->query($sql);
$row = $result->fetch();
return $row[0];
}
function getWeiFilename($maxver, $filename)
{
$dir = dirname(__FILE__);
$dir .= DIRECTORY_SEPARATOR . $filename;
if (is_file($dir)) {
return array($dir);
}
$files = array();
if (is_dir($dir) && ($dir_p = opendir($dir))) {
$ds = DIRECTORY_SEPARATOR;
while (($filename = readdir($dir_p)) !== false) {
if ($filename == ‘.‘ || $filename == ‘..‘ || $filename == ‘.svn‘) {
continue;
}
$dirs_p = $dir . DIRECTORY_SEPARATOR . $filename;
if (is_dir($dirs_p) && ($dir_ps = opendir($dirs_p))) {
while (($filenames = readdir($dir_ps)) !== false) {
if ($filenames == ‘.‘ || $filenames == ‘..‘) {
continue;
}
$files[] = $dirs_p . DIRECTORY_SEPARATOR . $filenames;
}
} else {
$files[] = $filename;
}
}
closedir($dir_p);
}
$arr = array();
for ($i = 0, $iMax = count($files); $i < $iMax; $i++) {
$u_file_name = basename($files[$i]);
$prearr = explode(‘.‘, $u_file_name);
$pre = ltrim($prearr[0], ‘0‘);
if ($pre > $maxver) {
$arr[] = $files[$i];
}
}
return $arr;
}
function populate_db($lnk, $DBPrefix, $sqlfile)
{
global $errors;
$query = fread(fopen($sqlfile, "r"), filesize($sqlfile));
$pieces = split_sql($query);
// 增加事务处理
$lnk->query(‘START TRANSACTION‘);
for ($i = 0, $iMax = count($pieces); $i < $iMax; $i++) {
$pieces[$i] = trim($pieces[$i]);
if (!empty($pieces[$i]) && $pieces[$i] != "#") {
$pieces[$i] = str_replace("#__", $DBPrefix, $pieces[$i]);
if (!$lnk->query($pieces[$i])) {
$errors[] = array($lnk->errorInfo());
$lnk->query(‘ROLLBACK‘);
break;
}
}
}
if (!$errors) {
$lnk->query(‘COMMIT‘);
return 1;
} else {
return $errors;
}
}
function split_sql($sql)
{
$sql = trim($sql);
$sql = preg_replace("/\n#[^\n]*\n/", "/\n/", $sql);
$buffer = array();
$ret = array();
$in_string = false;
for ($i = 0; $i < strlen($sql) - 1; $i++) {
if ($sql[$i] == ";" && !$in_string) {
$ret[] = substr($sql, 0, $i);
$sql = substr($sql, $i + 1);
$i = 0;
}
if ($in_string && ($sql[$i] == $in_string) && $buffer[1] != "\\") {
$in_string = false;
} elseif (!$in_string && ($sql[$i] == ‘"‘ || $sql[$i] == "‘") && (!isset($buffer[0]) || $buffer[0] != "\\")) {
$in_string = $sql[$i];
}
if (isset($buffer[1])) {
$buffer[0] = $buffer[1];
}
$buffer[1] = $sql[$i];
}
if (!empty($sql)) {
$ret[] = $sql;
}
return ($ret);
}
function colorize($text, $status)
{
$out = "";
switch ($status) {
case "SUCCESS":
case "Green":
$out = "[32m"; //Green
break;
case "FAILURE":
case "Red":
$out = "[31m"; //Red
break;
case "WARNING":
case "Yellow":
$out = "[33m"; //Yellow
break;
case "NOTE":
case "Blue":
$out = "[34m"; //Blue
break;
default:
throw new Exception("Invalid status: " . $status);
}
return chr(27) . "$out" . "$text" . chr(27) . "[0m";
}
project.sh
#!/bin/bash
# sqlversion.php
sqlversion_file=${cur_dir}/web-admin/sql_version/sqlversion.php
sed -i "s#^\$db_host.*;#\$db_host=‘${DB_HOST}‘;#g" $sqlversion_file
sed -i "s#^\$db_user.*;#\$db_user=‘${DB_USER}‘;#g" $sqlversion_file
sed -i "s#^\$db_pwd.*;#\$db_pwd=‘${DB_PWD}‘;#g" $sqlversion_file
sed -i "s#^\$db_name.*;#\$db_name=‘${DB_NAME}‘;#g" $sqlversion_file
Echo_Green "======> sqlversion.php init ok.";
# Conf/db.php
db_file=${cur_dir}/web-admin/Application/Common/Conf/db.php
sed -i "s#^\$db_host.*;#\$db_host=‘${DB_HOST}‘;#g" $db_file
sed -i "s#^\$db_user.*;#\$db_user=‘${DB_USER}‘;#g" $db_file
sed -i "s#^\$db_pwd.*;#\$db_pwd=‘${DB_PWD}‘;#g" $db_file
sed -i "s#^\$db_name.*;#\$db_name=‘${DB_NAME}‘;#g" $db_file
Echo_Green "======> Conf/db.php init ok.";
# Conf/uniform.php
uniform_file=${cur_dir}/web-admin/Application/Common/Conf/uniform.php
if [[ $APP_NAME != ‘‘ ]];then
sed -i "s#^\$app_name.*;#\$app_name=‘${APP_NAME}‘;#g" $uniform_file
fi
if [[ $APP_ID != ‘‘ ]];then
sed -i "s#^\$app_id.*;#\$app_id=‘${APP_ID}‘;#g" $uniform_file
fi
if [[ $APP_SECRET != ‘‘ ]];then
sed -i "s#^\$app_secret.*;#\$app_secret=‘${APP_SECRET}‘;#g" $uniform_file
fi
if [[ $MCHID != ‘‘ ]];then
sed -i "s#^\$mchid.*;#\$mchid=‘${MCHID}‘;#g" $uniform_file
fi
if [[ $WEIXIN_PAY_KEY != ‘‘ ]];then
sed -i "s#^\$weixin_pay_key.*;#\$weixin_pay_key=‘${WEIXIN_PAY_KEY}‘;#g" $uniform_file
fi
sed -i "s#^\$app_en_name.*;#\$app_en_name=‘${DB_NAME}‘;#g" $uniform_file
Echo_Green "======> Conf/uniform.php init ok.";
# 初始化Runtime
runtime=${cur_dir}/web-admin/Application/Runtime
if [ ! -d $runtime ];then
mkdir $runtime
chmod -R 777 $runtime
else
rm -rf $runtime/*
chmod -R 777 $runtime
fi
Echo_Green "======> runtime init ok.\n"
# site_upload
site_upload=${cur_dir}/web-admin/Public/site_upload
if [ ! -d $site_upload ];
then
mkdir $site_upload
chmod -R 777 $site_upload
else
chmod -R 777 $site_upload
fi
Echo_Green "======> site_upload init ok.\n"
taro.sh
#!/bin/bash
# 判断是否安装了node
if ! type node >/dev/null 2>&1; then
Echo_Red "node ";
exit 1;
fi
if ! type npm >/dev/null 2>&1; then
Echo_Red "npm not installed";
exit 1;
fi
if ! type yarn >/dev/null 2>&1; then
Echo_Red "yarn not installed";
exit 1;
fi
if ! type cnpm >/dev/null 2>&1; then
Echo_Red "cnpm not installed";
exit 1;
fi
if ! type taro >/dev/null 2>&1; then
Echo_Red "taro not installed";
exit 1;
fi
# 初始化
cd ${cur_dir}/web-bin/applet && cnpm install
Echo_Green "======> taro packages install ok.";
# 运行项目
# cd ${cur_dir}/web-bin/applet && npm run dev:weapp
cd ${cur_dir}/web-bin/applet && npm run build:weapp
Echo_Green "======> taro run ok.";
这种脑图,拆解写shell,很好用。
写脚本虽然费事,但是用起来能够省很多力气。