Post

Bash function to diff files before and after a change

Do want to log the changes you make to files?

Here are some functions todo just that

You may want to use this to copy paste into notes or you may be capturing your ssh session directly.

Function for Nano

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
nano () {
        nano=$(whereis -b nano | cut -d' ' -f2)
    if [ -e "$1" ] && [ $(stat --format="%s" "$1") -le 2500000 ]; then
        exec 3< <(cat "$1")
        "$nano" "$1"
        diff -c <(cat <&3) "$1"
        exec 3<&-
    elif [ $# -eq 0 ]; then
        echo "No filename given, opening a new file with nano"
        "$nano"
    elif [ ! -e "$1" ]; then
        echo "Error: File does not exist"
        $nano $1
    else
        echo "Error: File is larger than 25MB, cannot diff"
        $nano $1
    fi
}

Function for Vi

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
vi () {
        vi=$(whereis -b vi | cut -d' ' -f2)  
    if [ -e "$1" ] && [ $(stat --format="%s" "$1") -le 2500000 ]; then
        exec 3< <(cat "$1")
        "$vi" "$1"
        diff -c <(cat <&3) "$1"
        exec 3<&-
    elif [ $# -eq 0 ]; then
        echo "No filename given, opening a new file with vi"
        "$vi"
    elif [ ! -e "$1" ]; then
        echo "Error: File does not exist"
        $vi $1
    else
        echo "Error: File is larger than 25MB, cannot diff"
        $vi $1
    fi
}

Function for Vim

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
vim () {
        vim=$(whereis -b vim | cut -d' ' -f2)
    if [ -e "$1" ] && [ $(stat --format="%s" "$1") -le 2500000 ]; then
        exec 3< <(cat "$1")
        "$vim" "$1"
        diff -c <(cat <&3) "$1"
        exec 3<&-
    elif [ $# -eq 0 ]; then
        echo "No filename given, opening a new file with vim"
        "$vim"
    elif [ ! -e "$1" ]; then
        echo "Error: File does not exist"
        $vim $1
    else
        echo "Error: File is larger than 25MB, cannot diff"
        $vim $1
    fi
}
This post is licensed under CC BY 4.0 by the author.