Backing up files with one bash command

Jul 3, 2024·
Gert de Pagter
Gert de Pagter
· 2 min read

Recently I wanted to make some changes to my SSH config, but I didn’t want to accidentally break anything, and lose my correct config. So I manually did an mv ~/.ssh/config ~/.ssh/config_back, made some changes, and moved it back again. I had to do this a couple of times to try out different things, and realized I had done things like this quite some times just to make a quick backup with bash, and then move them back.

So with my (limited) bash skills I created 2 functions, that I now have in my .zshrc configuration file. The 2 functions are called bak and unbak, and will back up and restore a file respectively. If you want to use these 2 as well, just add then to your .bashrc or .zshrc (depending on your terminal), and if you reload, you can now simply do bak ~/.ssh/config and you have a backup of your config file.

bak() {
    input="$1"
    output="${base}_bak"
    
    if [[ -e "$input" ]]; then
        mv "$input" "$output"
        echo "Renamed '$input' to '$output'"
    else
        echo "File '$input' does not exist"
    fi
}

unbak() {
    input="$1"
    if [[ "$input" == *_bak ]]; then
        output="${input%_bak}"
        if [[ -e "$input" ]]; then
            mv "$input" "$output"
            echo "Renamed '$input' to '$output'"
        else
            echo "File '$input' does not exist"
        fi
    else
        echo "File '$input' does not end with '_bak'"
    fi
}

If you want to get notified of the next blog post, join the newsletter.