背景
我正在编写一个函数来附加到我的 $HOME
目录中名为 .bash.local
的文件中。
➡️ .bash.local
来自 .bash_profile
。
但是,我想有条件地追加到 .bash.local
当且仅当文件不已包含 $BASH_CONFIGS
。
要记住的事情
我选择的操作系统是 MacOS Mojave
,因此某些版本的命令行应用程序会有所不同(例如,Mac 上的 grep
是 BSD grep
而不是 GNU grep
)。
⚠️append_to_bash_local()
append_to_bash_local() {
local LOCAL_BASH_CONFIG_FILE="$HOME"/.bash.local
declare -r BASH_CONFIGS="
# TOOL_NAME - TOOL_DESCRIPTION.
# Add tool configurations here
"
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# If needed, add the necessary configs in the
# local shell configuration file.
if ! grep "^$BASH_CONFIGS" < "$LOCAL_BASH_CONFIG_FILE" &> /dev/null; then
# this block never runs, even if the contents of $BASH_CONFIG
# are NOT present in $HOME/.bash.local
fi
}
最佳答案
你很接近。不管怎样,小修正:
- 使用零分隔的
grep -Z
来匹配带有换行符的模式。如果你仔细想想的话,你会发现它有点hacky,但每次都有效。 - 使用
-q
进行 grep 使其保持静默。 - 并且不要将文件输入到 stdin 到 grep,只需告诉 grep 文件名即可。
- 检查文件是否存在
append_to_bash_local() {
local LOCAL_BASH_CONFIG_FILE="$HOME"/.bash.local
declare -r BASH_CONFIGS="
# TOOL_NAME - TOOL_DESCRIPTION.
# Add tool configurations here
"
if [[ "$(uname)" == "Linux" ]]; then
if
# if a file does not exists
[ ! -e "$LOCAL_BASH_CONFIG_FILE" ] ||
# if it doesn't have the content of BASH_CONFIGS
! grep -q -z "$BASH_CONFIGS" "$LOCAL_BASH_CONFIG_FILE"; then
echo appending
printf '%s\n' "$BASH_CONFIGS" >> "$LOCAL_BASH_CONFIG_FILE"
else
echo not appending
fi
elif [[ "$(uname)" == "Darwin" ]]; then
if
[ ! -e "$LOCAL_BASH_CONFIG_FILE" ] ||
! grep -q "$(<<<"$BASH_CONFIGS" tr '\n' '\01')" < <(
less "$LOCAL_BASH_CONFIG_FILE" | tr '\n' '\01'
); then
echo appending
printf '%s\n' "$BASH_CONFIGS" >> "$LOCAL_BASH_CONFIG_FILE"
else
echo not appending
fi
fi
}
关于string - 在bash中检查文件是否包含多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53900318/