tags:

views:

57

answers:

2

This question is based on this thread.

The code

function man()
{       
    man "$1" > /tmp/manual; less /tmp/manual 
}

Problem: if I use even one option, the command does not know where is the wanted-manual

For instance,

man -k find

gives me an error, since the reference is wrong. The command reads -k as the manual.

My attempt to solve the problem in pseudo-code

if no parameters
    run the initial code
if one parameter
    run: man "$2"
...

In other words, we need to add an option-check to the beginning such that

Pseudo-code

    man $optional-option(s) "$n" > /tmp/manual; less /tmp/manual

where $n

  • n=1 if zero options
  • n=2 if 1 option
  • n=3 if 2 options
  • ....

How can you make such an "option-check" that you can alter the value of $n?

Developed Problem: to make two if loops for the situations from n=1 to n=2

+2  A: 

How about passing all the arguments

function man()
{       
    man $@ > /tmp/manual; less /tmp/manual 
}

What is the bug in less which you mention in the title?

Adrian Panasiuk
$@ should probably be quoted. Otherwise `man "one two"` might be interpreted as `man one two`.
Noah Medling
+1  A: 

First, you can pass all of your function's arguments to man by using $* or $@. You can read man sh for the precise details on the difference between the two; short story is to almost always use "$@" with double quotes.

Second, the temporary file is unnecessary. You could make this a little cleaner by piping the output of man directly to less:

function man() {
    man "$@" | less
}

By the way, if you're just trying to use a different pager (man uses more and you want the fancier less) there's a commonly recognized PAGER environment variable that you can set to override the default pager. You could add this to your ~/.bashrc for instance to tell all programs to use less when displaying multiple screens of output:

export PAGER=less


To answer your precise question, you can check the number of arguments with $#:

if [ $# -eq 0 ]; then
    : # No arguments
elif [ $# -eq 1 ]; then
    : # One argument
# etc.

You might also find the shift command helpful. It renames $2 to $1, $3 to $2, and so on. It is often used in a loop to process command-line arguments one by one:

while [ $# -gt 1 ]; do
    echo "Next argument is: $1"
    shift
done

echo "Last argument is: $1"
John Kugelman
The $* does not work in OS/X.
Masi
I'm on a Mac and it works. You just need an sh-compatible shell.
John Kugelman