noobcoder
noobcoder

Reputation: 6671

Run script when a command is executed irrespective of the command's arguments

rm -rf
rm -r
rm -f
rm

When any of these commands are run I want them to run a certain script.

Something like alias ?='some_script.sh'

(the question mark in this case means the rm command with any arguments.)

How can this be done? I don't HAVE to use aliases, anything that works is fine.

Upvotes: 1

Views: 59

Answers (2)

chepner
chepner

Reputation: 531245

Don't use an alias; define a function:

rm () {
    some_script.sh
    command rm "$@"
}

The standard disclaimer when modifying the behavior of rm in any way applies. Don't do this is some_script.sh is intended to be a safety net of some kind. You may become reliant on it, and be unpleasantly surprised if you run rm on a machine without this safety net installed.

Upvotes: 2

Inian
Inian

Reputation: 85663

If your requirement is to run the script on every bash command, then best way is to append it to a special variable in bash, which gets executed every time a command is entered in the prompt.

The PROMPT_COMMAND variable, all you need to do is append your script some_script.sh to it like

$ PROMPT_COMMAND+="some_script.sh;"

Or if you want to script only for the command rm, then keeping an alias is the best way to do it. Add the line in your ~.bashrc and source it after making the change.

alias rm="some_script.sh; rm"

Upvotes: 1

Related Questions