[英]Pretty-print for shell script
Vim 可以縮進 bash 腳本。 但在縮進之前不要重新格式化它們。
備份你的 bash 腳本,用 vim 打開它,輸入gg=GZZ
,縮進將被更正。 (不耐煩的注意:這會覆蓋文件,所以一定要備份!)
雖然,一些帶有<<
(期望 EOF 作為一行的第一個字符)的錯誤,例如
編輯:ZZ 不是 ZQ
在 bash 我這樣做:
reindent() {
source <(echo "Zibri () {";cat "$1"; echo "}")
declare -f Zibri|head --lines=-1|tail --lines=+3 | sed -e "s/^\s\s\s\s//"
}
這消除了注釋並重新縮進腳本“bash 方式”。
如果您的腳本中有 HEREDOCS,它們就會被前一個函數中的 sed 破壞。
所以使用:
reindent() {
source <(echo "Zibri () {";cat "$1"; echo "}")
declare -f Zibri|head --lines=-1|tail --lines=+3"
}
但是你所有的腳本都會有一個 4 個空格的縮進。
或者你可以這樣做:
reindent ()
{
rstr=$(mktemp -u "XXXXXXXXXX");
source <(echo "Zibri () {";cat "$1"|sed -e "s/^\s\s\s\s/$rstr/"; echo "}");
echo '#!/bin/bash';
declare -f Zibri | head --lines=-1 | tail --lines=+3 | sed -e "s/^\s\s\s\s//;s/$rstr/ /"
}
這也照顧heredocs。
派對有點晚了,但看起來shfmt可以幫你解決問題。
bash5+ 有一個 --pretty-print 選項.. 它會刪除注釋,包括第一行 '#!/bin...'
shfmt工作得很好。
您可以格式化 bash 腳本,還可以檢查預提交鈎子的格式。
# reformat
shfmt -l -w script.sh
# check if the formatting is OK
shfmt -d script.sh
# works on the whole directory as well
shfmt -l -w .
唯一不存在的選項是它不會根據行長(尚未)重新格式化。
由於它是用 go 編寫的,因此您可以下載大多數平台的二進制文件,例如 Travis ( .travis.yml
):
install:
- curl -LsS -o ~/shfmt https://github.com/mvdan/sh/releases/download/v3.1.2/shfmt_v3.1.2_linux_amd64
- chmod +x ~/shfmt
script:
- ~/shfmt -d .
npm上還有交叉編譯的js版本和很多編輯器插件(見相關項目)
找到了這個http://www.linux-kheops.com/doc/perl/perl-aubert/fmt.script 。
非常好,我拿出的一件事就是[...] - >測試替換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.