3

I am using R a lot. In R, you can call a man page for a function by writing

?print

I got used to that so much that I intermittently type that in a bash shell window as well. Now, I have set up an alias

?='man'

that almost cuts it: I can do, for example, ? ls. However, I would prefer it to work with ?ls. Unfortunately, this one does not work. Is there any way to make bash call the man page when I type the question mark without the space after?

January
  • 16,320
  • 6
  • 52
  • 74
  • AFAIK there isn't a way to do this since bash uses spaces to split up command line arguments: if you typed `?ls` (with `?` being the command and `ls` being the argument) bash wouldn't be able to tell what the command was: it could be `?`, or `?l`, or `?ls`, with the arguments being `ls`, `s`, or ` ` respectively. – benwad Oct 12 '12 at 13:57
  • I was thinking more in the direction of command prompt executables. – January Oct 12 '12 at 13:59
  • That's the problem: bash doesn't know whether `ls` should be considered a command prompt executable until it sees that the command is `man` (or `?`). And it doesn't know that until it sees a space after the command. – benwad Oct 12 '12 at 14:05
  • 4
    People should really learn to leave a comment when they downvote. This is a perfectly good programming question – nico Oct 12 '12 at 14:06

1 Answers1

11

bash provides a hook for handling undefined commands. Since you are unlikely to ever have any commands whose names start with ?, you can use this hook to process any attempt to run such a command:

command_not_found_handle () {
    if [[ $1 =~ ^\? ]]; then
        cmd=${1#\?}
        man $cmd
    else
        echo "$1: command not found" >&2
        return 127
    fi
}

This function would go into your .bashrc file, so that is it available in any shell. When you try to execute

$ ?ls

the command is not found, the hook intercepts the failed attempt to find the command, determines that the command name starts with ?, then strips the ? and passes the result as an argument to man. Other undefined commands merely produce an error message similar to the default bash error for unfound commands and exits with status 127 (the same status bash usually uses to denote command not found).

chepner
  • 497,756
  • 71
  • 530
  • 681
  • This is wicked. Thank you very much! – January Oct 12 '12 at 14:06
  • 4
    Be careful, though, `?` has a special meaning in bash. Try `touch cls ; ?ls`. – choroba Oct 12 '12 at 14:12
  • @choroba: Very good point. I'm not sure there's any way around that aside from disabling pattern expansion with `set -f`. But if you find a situation where `?whatever` matches a file in the current directory, you can try again with `\?whatever`. The matched file shouldn't run as long as '.' isn't in your `PATH` (which it shouldn't be, for security reasons). – chepner Oct 12 '12 at 14:32