Linux/Unix: Quickly accessing the man page on a command switch

📄 Wiki page | 🕑 Last updated: Nov 2, 2022

Instead of first opening the man page with man command and then searching for the command switch/option, you can do that in a quick, single step.

tl;dr

Function:

function msw() {
  man "$1" | less -p "^\s+$2"
}

Example use (the first argument is the name of the command, the second argument is command switch/option):

msw less -p

This should take you directly to the -p option on the less man page.

Details

We're defining a function called msw which is basically just a wrapper around man:

function msw() {
  man "$1"
}

The next is step is to take the output (the whole man page of the command) and pass it as an input (stdin) to less:

function msw() {
  man "$1" | less -p "^\s+$2"
}

We're using -p (shorthand for --pattern) option of less to tell it to skip until the first occurrence of that regex pattern.

Pattern ^\s+$2 will match the line that starts with one or more whitespace characters, followed by our second argument to the script.

Note: To learn more about less -p, you can now use our new function: msw less -p :)

Script

You can put the above function in your shell init file (e.g. ~/.bashrc), or create a script like this somewhere in your $PATH:

#!/bin/bash

man "$1" | less -p "^\s+$2"

And make it executable:

chmod +x ./msw

The advantage of this over the function is that it will be available everywhere, not only in your current shell.