
私は多くのプログラム(homebrew、gitなど)がインストールされているスクリプトを持っており、その過程で行われたすべての作業を記録するようにしていますが、フラグを渡してログをオフにしたいとstdout
思います。--no-log
。ロギング機能は複数のヘルパースクリプトを含むファイルから開始されるため、これらの他のファイルにフラグを渡すことはできません。
[編集する]
与えられた(./bin/install.sh)
#!/usr/bin/env bash
# Test for known flags
for opt in $@
do
case $opt in
--no-log) export SILENT=true ;;
-*|--*)
e_warning "Invalid option $opt"
run_help
;;
esac
done
source ./lib/utils
e_process "Installing Homebrew"
ruby -e "$(curl -#fkL raw.github.com/Homebrew/homebrew/go/install)"
そして(./lib/utils.sh)
#!/usr/bin/env bash
logging() {
# write your test however you want; this just tests if SILENT is non-empty
if [ -n "$SILENT" ]; then
"$@" &> /dev/null
else
"$@"
fi
}
# Command/Processing logging
e_process() {
logging printf "$(tput setaf 6)┃ $(tput sgr0)$(tput setaf 7)%s...$(tput sgr0)\n" "$@"
}
それから
実行すると./bin/dotfiles
ロギングが表示されると予想されますが、┃ Installing Homebrew...
実行すると./bin/dotfiles --no-log
ロギングは表示されませんが機能しません。
出力(使用bash -x
)
$ bash -x ./bin/install.sh
+ source ./lib/utils.sh
+ e_process 'Installing Homebrew'
++ tput setaf 6
++ tput sgr0
++ tput setaf 7
++ tput sgr0
+ logging printf '┃ %s...\n' 'Installing Homebrew'
+ '[' -n '' ']'
+ printf '┃ %s...\n' 'Installing Homebrew'
┃ Installing Homebrew...
使用--no-log
bash -x ./bin/install.sh --no-log
+ for opt in '$@'
+ case $opt in
+ export SILENT=true
+ SILENT=true
+ source ./lib/utils.sh
+ e_process 'Installing Homebrew'
++ tput setaf 6
++ tput sgr0
++ tput setaf 7
++ tput sgr0
+ logging printf '┃ %s...\n' 'Installing Homebrew'
+ '[' -n true ']'
+ printf '┃ %s...\n' 'Installing Homebrew'
答え1
utils スクリプトを取得します。今後環境変数の値を設定するので、グローバル変数は$silent_mode
空です。
ユーティリティスクリプトで "temp"変数を使用しないでください。$SILENT
この関数で引き続き使用してください。