So I'm trying to append the contents of one file to another file, if it's not already included. This is how I try:
catAndAppendIfMissing(){
[[ ! -s $2 ]] && touch "$2" || [[ ! -s $2 ]] && sudo touch "$2"
if grep $1 $2; then
echo "found"
else
catAndAppend $1 $2 #this appends file $1 contents to file $2 (and takes care of adding newlines if needed and uses sudo if needed, thus the separate function)
fi
}
With if grep $1 $2
I'm trying to see if file $1 contents are present in file $2. That's the part that doesn't work as intended:
When I run this twice on the same file, it will simply append the same text twice to the destination file.
How can I solve that?
Precisions:
- I'm on OSX 10.11.5 (but a solution for Linux / cross-platform could also be relevant both for me at home or for someone else reading this)
- My choice of using catAndAppend over
cat $file1 >> $file2
is to handle cases where sudo is needed and separate the appended stuff from what's already there by adding newlines as needed. - I don't wish to append if file $1 is anywhere in file $2 (not only at the beginning or the end)
- For info, here's one of the files $1 contents that I tried against:
.
alias ls='ls -a'
alias mkdir="mkdir -pv"
alias wget="wget -c"
alias histg="history | grep"
alias echopath='echo $PATH | tr -s ":" "\n"'
alias myip="curl -sSL http://ipecho.net/plain | xargs echo"
alias webpic="mogrify -resize 690\> *.png"
alias cddog='cd ~/dev/go/src/github.com/dogtools/dog'
alias xp='cd ~/dev/go/src/experiments'
- but I will need to use it with other files containing var exports, code, commands, configs, any kind of text basically