#!/bin/bash # Copyright (C) 2014 Ian Kelling # This program is under GPL v. 3 or later, see appendu() { local help="Usage: appendu [OPTION]... FILE [LINE]... Append unique. Append each line to FILE if it does not exist in FILE. Use LINE if specified, else use lines from stdin. Appended lines are output to the terminal. -s don't try to use sudo when it would help us read or write the file -- stop processing arguments --help display this message" local dosudo=true while true; do if [[ $1 == --help ]]; then echo "$help" return elif [[ $1 == -s ]]; then dosudo=false shift elif [[ $1 == -- ]]; then shift break else break fi done if [[ ${#@} == 0 ]]; then echo "error: need 1 or more arguments" echo "$help" return 1 fi local readsudo writesudo x local file="$1" shift if [[ -e $file ]]; then [[ -r $file ]] || readsudo=sudo [[ -w $file ]] || writesudo=sudo else local dir="$(dirname "$file")" if [[ -d $dir ]]; then [[ ! -w $dir ]] && writesudo=sudo else echo "appendu error: $dir does not exist" return 1 fi fi if ! $dosudo; then readsudo= writesudo= fi if (( $# )); then for x in "$@"; do [[ -e "$file" ]] && $readsudo grep -q "^$x$" "$file" || $writesudo tee -a "$file"<<<"$x" done elif [[ ! -t 0 ]]; then unset IFS while read -r x; do # duplicated from above [[ -e "$file" ]] && $readsudo grep -q "^$x$" "$file" || $writesudo tee -a "$file"<<<"$x" done fi }