前言
需求是批量修改.crt和.key为ssl.chain.crt和server.key,为什么会有这样的需求主要是踩了一个大坑Sectigo AddTrust External CA Root Expiring May 30, 2020,说多了都是泪。
更新历史
2020年05月31日 - 初稿
阅读原文 - https://wsgzao.github.io/post/bash-recursive/
解题思路
- 需要遍历目录
- 需要重命名.key和.crt结尾的文件为server.key和ssl.chain.crt
linux命令 递归修改文件名(包括文件夹)
网上搜索了关键词,发现这个脚本写得比较清晰,但还是需要修改下
#!/bin/bash
function changeName(){
#new=`echo $1|sed 's/^/abc/g'`
new=`echo $1|sed -r 's/abc(.*$)/\1/g'`
echo changeName old: $1 new: $new
if [ $1 != $new ];then
mv $1 $new
fi
}
function travFolder(){
#echo "travFolder start"
flist=`ls $1`
cd $1
for f in $flist
do
#echo traverse do $f
local old=$f
if test -d $f
then
#echo "traverse dir:${f}"
travFolder $f
#echo "traverse rename dir:${f}"
changeName $old #rename folder
else
#echo "traverse file:$f"
changeName $f
fi
done
cd ../
}
param=$1
if [ -z "$1" ]
then
param="./"
echo "empty string: $param"
else
param=$1
fi
travFolder $param
修改后的代码
如果你考虑使用rename简化代码,可以参考Stack Overflow的一篇文章
How to Batch Rename Files in a macOS Terminal?
#!/bin/bash
function travFolder(){
#echo "travFolder start"
flist=`ls $1`
cd $1
for f in *.key; do mv "$f" "server.key"; done
for f in *.crt; do mv "$f" "ssl.chain.crt"; done
for f in $flist
do
#echo traverse do $f
if test -d $f
then
#echo "traverse dir:${f}"
travFolder $f
fi
done
cd ../
}
param=$1
if [ -z "$1" ]
then
param="./"
echo "empty string: $param"
else
param=$1
fi
travFolder $param