fc - macOS


Overview

The fc command in macOS is used for listing, editing, and re-executing commands from the command history. It is an essential utility for users who frequently work in the terminal, allowing them to effectively manage and manipulate their command history. This tool can be particularly useful for editing previous long or complicated commands quickly or reviewing past command sequences.

Syntax

The basic syntax of the fc command is:

fc [-r] [-e editor] [first [last]]
fc -l [-nr] [first [last]]
  • first: Specifies the first command to be affected.
  • last: Specifies the last command to be affected.

If first or last is omitted, fc behaves according to its default settings, which might vary slightly depending on the shell.

Options/Flags

  • -e <editor>: Specifies the editor to use for editing commands. If no editor is specified, fc will use the default editor set by the FCEDIT or EDITOR environment variables, or vi if neither is set.
  • -l: Lists commands rather than invoking an editor on them. The commands are displayed in the order they were entered.
  • -n: Suppresses command numbers when listing with -l.
  • -r: Reverses the order of commands listed or edited.

Examples

  1. Edit the Most Recent Command:

    fc
    

    This will open the most recent command in the default editor.

  2. List the Last 5 Commands:

    fc -l -5
    

    Lists the last five commands executed in the shell.

  3. Edit a Specific Range of Commands by Numbers:

    fc 102 105
    

    Opens commands 102 through 105 in the default editor.

  4. Use a Specific Editor:

    fc -e nano 150
    

    Edits the command numbered 150 using nano as the editor.

Common Issues

  • Editor Not Configured: If no editor appears when invoking fc, ensure the EDITOR or FCEDIT environment variable is set:
    export EDITOR=nano
    
  • Command Not Found: Users might reference commands out of the range of their history index. Always check your command index using history.

Integration

fc can be combined with other UNIX tools for advanced command history management. For example, to review and re-execute a previously failed command after editing:

fc -ln -1 | tail -n 1 | xargs -I {} sh -c {}

This retrieves the last command, allows you to edit it in the default editor, and executes it.

  • history: Lists or manipulates the history list.
  • grep: Used to filter history output for specific commands.
  • sed: Can be utilized to manipulate the output of commands for automation tasks.

For broader command editing and scripting capabilities, consider delving into shell scripting tutorials, where you can combine fc with loops, conditionals, and file operations for more complex workflows.