我正在使用以下 shell 命令将字符串附加到文件中:

echo "latest stable main" | sudo tee -a /etc/my-app.conf > /dev/null

然而,这不是幂等的,即如果该字符串已存在于 /etc/my-app.conf 中,则每次调用该命令时都会多次附加该字符串。是否可以仅在巧妙的单行中不存在的情况下追加?

最佳答案

简短的回答:简单、容易和错误

如果您不关心极端情况下的正确性(多行输入、并发调用等),以下内容将完成这项工作:

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

关于linux - 制作 echo "foo"| sudo tee - 幂等,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53641899/

10-15 01:21