我正在使用以下shell命令将字符串附加到文件中:
echo "latest stable main" | sudo tee -a /etc/my-app.conf > /dev/null
但这不是幂等的,即,如果该字符串已经存在于/etc/my-app.conf
中,则每次调用该命令时都会附加多次。如果仅在聪明的单行代码中不存在,是否可以追加?
答案 0 :(得分:2)
如果您不在乎极端情况下的正确性(多行输入,并发调用等),则以下操作将 sorta 完成:
grep -Fxe 'latest stable main' /etc/my-app.conf || {
sudo tee -a /etc/my-app.conf <<<"latest stable main"
}
要想获得一个更注重正确性而不是简洁性的答案,请继续阅读。
作为一个简短的答案,但确实一定要注意正确性(包括同时调用以下多个实例时的正确操作):
#!/bin/bash
# ^^^- shebang present as an editor hint; this file should be sourced, not executed.
case $BASH_VERSION in ''|[0-3].*|4.0.*) echo "ERROR: Bash 4.1 or newer required" >&2; return 1 >/dev/null 2>&1; exit 1;; esac
appendEachNewLine() {
local file=$1 line out_fd
local -A existingContents=( ) # associative array, to track lines that already exist
# dynamically assign a file descriptor on which to both lock our file and write
exec {out_fd}>>"$file"
flock -x -n "$out_fd" || {
echo "ERROR: Unable to lock destination file" >&2
exec {out_fd}>&-
return 1
}
# read existing lines once, through a new file descriptor, only after holding the lock
while IFS= read -r line; do
existingContents[$line]=1
done <"$file"
# then process our stdin, appending each line if not previously seen
while IFS= read -r line; do
if ! [[ ${existingContents[$line]} ]]; then
printf '%s\n' "$line" >&"$out_fd"
fi
done
# close the file, thus releasing the lock, when done.
exec {out_fd}>&-
}
appendEachNewLineAsRoot() {
sudo bash -c "$(declare -f appendEachNewLine)"'; appendEachNewLine "$@"' appendEachNewLine "$@";
}
在source
编写完上面的脚本之后,作为如何使用它替换旧命令的示例:
echo "latest stable main" | appendEachNewLineAsRoot /etc/my-app.conf
答案 1 :(得分:0)
您还可以使用Ansible inline模块来确保文件中包含特定行。