1.为什么需要

由于重复性的工作很多,并且这些是固定的,所以我们需要使用脚本。

例如Hexo本地预览:

1
2
cd /Users/xulei/Documents/HexoBlog
hexo s

例如Hexo的更新—进入到Hexo博客的根目录并执行部署命令:

1
2
3
4
5
6
7
8
9
cd /Users/xulei/Documents/HexoBlog
echo "开始执行hexo clean"
hexo clean
echo "开始执行hexo g && gulp"
hexo g && gulp
echo "开始执行hexo d"
hexo d
echo "连接小石头的云服务器,拉取博客最新内容更新"
ssh -i /Users/xulei/Documents/云服务器/centos_xl root@182.254.228.71 "cd / ; ./run.sh"

2.制作脚本

1
2
3
4
5
# 创建脚本
vi name.sh

# 执行脚本
bash name.sh的绝对路径

参考:Mac 制作一个可执行脚本

3.脚本制作如何传入参数

例如在桌面创建一个支持传入名字的脚本文件

1
2
3
4
5
6
7
8
# newsh.sh
cd /Users/xulei/Desktop
filename=$1
vi $1.sh
open $1.sh

# 执行 在桌面创建一个test.sh文件并打开
bash newsh.sh test

4.批量替换

如果执行bash /Users/xulei/Desktop/commandr.sh https:\/\/fanandjiu.com\/ \/命令,那么就会针对/Users/xulei/Documents/HexoBlog/source/_posts文件夹下所有文件,首先判断是否包含字段https://fanandjiu.com/,如果包含就会替换成/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# bash /Users/xulei/Desktop/commandr.sh https:\/\/\/fanandjiu.com\/ \/
text=$1
newtext=$2

# 进入操作的文件目录下
cd /Users/xulei/Documents/HexoBlog/source/_posts

# grep所有有text的文件
for file in `grep -rn $text .`
do
# cut 出绝对路径
file_name=`echo $file | cut -d ':' -f 1`
echo "in [$file_name] want replace [$text] to [$newtext]"
# sed 就是把所有file_name 文件中的text 全部替换为newtext,至此达到目标
sed -i "" "s#${text}#${newtext}#g" ${file_name}
done