Bash 代碼優(yōu)化思考
最近我在思考這樣一個(gè)問題,順便看一下gpt對(duì)這個(gè)問題的解釋。搜索發(fā)現(xiàn):
團(tuán)隊(duì)寫代碼,為什么要遵循coding guideline?
繼續(xù)搜索:
對(duì)于一個(gè)使用bash為主要語(yǔ)言的項(xiàng)目,業(yè)界推薦的coding guideline?
這些規(guī)范有助于提高 Bash 代碼的可讀性、可維護(hù)性和可靠性。
然后我搜索 "bash script style guideline",最上面的結(jié)果是:

即代碼規(guī)范:https://google.github.io/styleguide/shellguide.html
我仔細(xì)閱讀了這份風(fēng)格指南,對(duì)其中的“局部變量”的章節(jié)很感興趣。
文中說:「最好把局部變量的定義與賦值,換行實(shí)現(xiàn),不要寫到同一行上」,以免掩蓋報(bào)錯(cuò)狀態(tài)碼。
我動(dòng)手驗(yàn)證這個(gè)細(xì)節(jié),發(fā)現(xiàn)果然如此:

然后我開始自查當(dāng)前的項(xiàng)目,尋找類似于如下風(fēng)格的代碼:
local my_var="$(my_func)"優(yōu)化后的預(yù)期結(jié)果:
local my_var
my_var="$(my_func)"在 https://regex101.com/ 測(cè)試代碼的運(yùn)行。給出范例
regex:
local fn=$(echo $name_ver| tr ':' '-').tar.xz
test string
local fn=$(echo $name_ver| tr ':' '-').tar.xz #普通
local fn=$(echo $name_ver| tr ':' '-').tar.xz # 模擬多個(gè)空格
local fn=$(echo $name_ver| tr ':' '-').tar.xz # 模擬tab縮進(jìn)
local fn="$(echo $name_ver| tr ':' '-').tar.xz" # 模擬帶引號(hào)的變量聲明測(cè)似乎生成的代碼
$1local $2\n$1$2=$3生成的代碼
$re = '/^(\s*)local\s+(\w+)=("?\$\(.*)/m';
$str = ' local fn=$(echo $name_ver| tr \':\' \'-\').tar.xzt
local fn=$(echo $name_ver| tr \':\' \'-\').tar.xzt
local fn=$(echo $name_ver| tr \':\' \'-\').tar.xz
local fn="$(echo $name_ver| tr \':\' \'-\').tar.xz"';
$subst = "$1local $2\n$1$2=$3";
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;精簡(jiǎn)為 perl_oneliner:

perl -pe 's/^(\s*)local\s+(\w+)=("?\$\(.*)/$1local $2\n$1$2=$3/g' -i file.txt測(cè)試的場(chǎng)景:
搜索代碼
pcregrep -lr '^(\s*)local\s+(\w+)=("?\$\(.*)' *
批量修正:
perl -pi -e 's#^(\s*)local\s+(\w+)=("?\$\(.*)#$1local $2\n$1$2=$3#' $(pcregrep -l -r '^(\s*)local\s+(\w+)=("?\$\(.*)' * )修正之后,仔細(xì)閱讀diff,檢驗(yàn)效果,發(fā)現(xiàn)符合預(yù)期。
后續(xù):增加git hook檢測(cè)代碼
為了讓以后新增的代碼,也都符合上述規(guī)范,我增加了這樣一個(gè)pre-commit腳本。這樣,每次提交之前,它都會(huì)幫我確保代碼合規(guī)。
同時(shí),我在編輯器里,設(shè)置了shfmt、shellcheck之類的規(guī)范,并設(shè)置為format on save,即保存時(shí)自動(dòng)格式化,來自動(dòng)處理格式問題。
# test code
if ! grep -wq 'Code violates rules' .git/hooks/pre-commit; then
cat >> .git/hooks/pre-commit <<'GIT_PRE_COMMIT_EOF'
#!/usr/bin/env bash
if find . -name '*.sh'| xargs pcregrep '^\s+local\s+\w+="?(`|\$\()'; then
echo "Error: Code violates rules"
echo 'use: local var'
echo 'var="$(...")'
echo 'instead of local var=``'
echo 'or local var="$(...)"'
echo 'as of explained in https://google.github.io/styleguide/shellguide.html'
exit 1
fi
GIT_PRE_COMMIT_EOF
chmod +x .git/hooks/pre-commit
fi總結(jié):
links
以上是文章的主要內(nèi)容,作為融合云/多云管理/私有云/FinOps 廠商,云聯(lián)壹云會(huì)持續(xù)關(guān)注這些領(lǐng)域的動(dòng)態(tài),分享相關(guān)的信息和技術(shù),可以通過的官網(wǎng)或關(guān)注的公眾號(hào)(云聯(lián)壹云)來獲取最新的信息,感謝大家的時(shí)間。
其他推薦閱讀
云聯(lián)壹云融合云管理平臺(tái)的 10 大應(yīng)用場(chǎng)景
SkyPilot:構(gòu)建在多云之上的ML和數(shù)據(jù)科學(xué),可節(jié)約3倍以上成本
Flexera 2023 云狀態(tài)報(bào)告解讀

