Monday, July 23, 2012

bash fc - fix command cheatsheet

bash's BUILTIN fc command (fix command) is very useful and generally under-utilised. Here is a quick cheatsheet of some common fc commands which can be very useful indeed.

Personally it was hard to recall and decrypt the man bash fc section, so I wrote up a little cheatsheet for future reference, as follows.
$ fc -l 5680 5690
This will echo the commands in the shell history from 5680 5690. No execution.
$ fc -l -5 (minus the letter L and minus the number one)
This will echo the last 5 commands in the shell history, the same as history 5. No execution.

CAREFUL! The following commands require care, so that you don't inadvertently execute commands on your system! Please read how they work and how to handle them before trying them for yourself!
$ fc 5699 (careful!)
This opens the editor stored in FCEDIT, falling back on EDITOR. If neither env var is set, vi is used.
The editor will be populated with history line 5699 in this example.
When editing is complete, the commands are echoed and executed!
If you don't want to execute anything, ensure the file is empty and save and exit.
$ fc 5680 5690 (careful!)
Same as above but the editor will contain the commands within the shell history range.
If you don't want to execute anything, ensure the file is empty and save and exit.
$ fc -10 -1 (careful!)
Same as above but the editor will contain the last 10 commands in the shell history.
If you don't want to execute anything, ensure the file is empty and save and exit.
$ fc -s number|command (careful!)
Where number matches a shell history number OR command will match the the most recent shell history command that begins with command, then execute the command.
$ fc -s match=replacement number|command (careful!)
Same as above and each instance of match is replaced by replacement, then execute the command.

Feel free to checkout man bash to learn more in depth about this command including some options I didn't cover here.

2 comments:

Unknown said...

Thanks for the tutorial.
As you said, the documentation in the man page is not very clear...

Felipe said...

What does the shell use for MATCH ? Extended Regular Expressions? Or BRE? Or ... ?