Correct misspelled commands with thefuck

1 minute read

No one can guarantee that he never make mistakes while using command line, even an experienced user.

Lucky enough, Vladimir Iakovlev created thefuck to corrects the previously misspelled command. It is written in python and works on both macos and Ubuntu system, install it with:

# for macos
brew install thefuck

# for ubuntu
pip3 install --user thefuck

You can get thefuck updated with:

pip3 install thefuck --upgrade

Configuration

Before using thefuck, you need to configure it by adding eval $(thefuck --alias) to either .bash_profile or .bashrc depending on what os you are using:

# for macos
echo 'eval $(thefuck --alias)' >> $HOME/.bash_profile

# for ubuntu
echo 'eval $(thefuck --alias)' >> $HOME/.bashrc

If you don’t want to use the fuck to trigger correction, you can change to whatever you want with:

eval $(thefuck --alias FUCK)

How to use

Using thefuck to correct command is fairly straight forward, when you get wrong command typed, type fuck, and you will get prompt like this:

thefuck

If the command showing in the prompt is correct, type enter to confirm or press letter n to select next, you can also use the arrow key to navigate through the candidates.

If there is only one option you can use fuck -y or fuck --yeah to skip the promption.

Create new rules

thefuck already have many rules about how to correct your command, and it is easy to expand it with our own, here I will create a rule to correct me if I missing -r option when copying directory.

Create a file named cp_recursive.py in directory .config/thefuck/rules like this:

import re
from thefuck.utils import for_app

@for_app('cp')
def match(command):
    output = command.output.lower()
    return 'omitting directory' in output or 'is a directory' in output

def get_new_command(command):
    return re.sub(r'^cp', 'cp -r', command.script)

Now, you can try this out.