mik01aj
mik01aj

Reputation: 12382

How to add something at the beginning of every Bash command?

I'd like to change my Bash configuration, so when I type something (e.g. foo bar) in the command prompt, it really executes h foo bar.

I want to do it because I often use hilite (aliased as h) to color stderr in red, and I would like to make this behaviour permanent.

Other use I see would be interacting with Git, as I write lots of commands like:

git status
git add ...
git commit ...

I guess I could use preexec_invoke_exec to execute something before the command is being run, but I don't know how can I change the command or prevent it from executing.

Any ideas?

Upvotes: 3

Views: 544

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

You can achieve this by binding the return key to insert the h for you. You can do this by adding this to your .input.rc:

Return: "\C-ah\ \n"

or put this bind in your .bashrc:

bind 'RETURN: "\C-ah \n"'   

(Kudos to these guys).

There are a few catches: obviously, it's bash-only, and this can give some pretty strange behavior in places (I can't think of a decent example right now), so I wouldn't say this is 'good' bashing in any way.

I would personally skip hilite and keep it all pure bash. So instead, try to look for a way to append something to each command so as to redirect the stderr stream to a colorized echo/printf...but that's a matter of preference I guess :)

Upvotes: 3

ghoti
ghoti

Reputation: 46826

To run a different command from the one you've specified, your best bet may be to maks a bash function of the commands to be caught.

I don't know anything about "hilite", but if it installs a binary, at, say /usr/bin/hilite, you could use:

git () {
  /usr/bin/hilite /usr/bin/git "$@"
}

So ... when you run git at your bash prompt, bash will actually run hilite, using /usr/bin/git and the rest of your command line arguments as the arguments to h.

Note that this should work in traditional Bourne shell as well as bash.

Upvotes: 0

Related Questions