PM2 运行Bash脚本

pm2 start app.js
pm2 start app.sh

脚本示例

updateblog 脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// run-script-node.js
const express = require('express');
const { exec } = require('child_process');

const app = express();
const PORT = 3764;

// 中间件解析 JSON 请求体
app.use(express.json());

// 路由:运行指定目录下的 Bash 脚本
app.get('/updateblog', (req, res) => {

const scriptPath = "/www/updateBlog.sh";

exec(`bash ${scriptPath}`, (error, stdout, stderr) => {
if (error) {
console.error(`Error executing script: ${error.message}`);
return res.status(500).send(`Error executing script: ${error.message}`);
}

if (stderr) {
console.error(`Script stderr: ${stderr}`);
return res.status(500).send(`Script stderr: ${stderr}`);
}

console.log(`Script stdout: ${stdout}`);
res.send(`Script executed successfully: ${stdout}`);
});
});

app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

存储库更新脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
cd /opt/1panel/apps/openresty/openresty/www/sites/blog.rezedge.com/source/_posts

BRANCH=master

LOCAL=$(git log $BRANCH -n 1 --pretty=format:"%H")
REMOTE=$(git log remotes/origin/$BRANCH -n 1 --pretty=format:"%H")

if [ $LOCAL = $REMOTE ]; then
echo "Up-to-date"
else
echo "Need update"
git fetch --all
git reset --hard origin/master
git pull
cd /opt/1panel/apps/openresty/openresty/www/sites/blog.rezedge.com
hexo generate
rm -r ./index/
mv ./public/ ./index/
fi