Reputation: 2570
Is it possible to add an option to an existing Bash command?
For example I would like to run a shell script when I pass -foo to a specific command (cp, mkdir, rm...).
Upvotes: 3
Views: 3557
Reputation: 184
Some programmer dude's code may look cool and attractive... but you should use it very carefully for most commands: https://unix.stackexchange.com/questions/41571/what-is-the-difference-between-and
About usage of $* and $@:
You shouldn't use either of these, because they can break unexpectedly as soon as you have arguments containing spaces or wildcards.
I was using this myself for at least months until I realized it was the reason why my bash code sometimes didn't work.
Consider much more reliable, but less easy and less portable option. As pointed out in comments, recompile original command with changes, that is:
Download c/c++ source code from some respected developers repositories:
Add some code in c/c++, compile with gcc/g++.
Also, I guess, you can edit bash itself to set it to check if a string passed to bash as a command matches some pattern, don't execute this and execute some different command or a bash script
If you really are into this idea of customizing and adding functionality to your shell, maybe check out some other cool fashionable shells like zsh, fish, probably they have something, I don't know.
Upvotes: 0
Reputation: 409166
You can make an alias for e.g. cp
which calls a special script that checks for your special arguments, and in turn call the special script:
$ alias cp="my-command-script cp $*"
And the script can look like
#!/bin/sh
# Get the actual command to be called
command="$1"
shift
# To save the real arguments
arguments=""
# Check for "-foo"
for arg in $*
do
case $arg in
-foo)
# TODO: Call your "foo" script"
;;
*)
arguments="$arguments $arg"
;;
esac
done
# Now call the actual command
$command $arguments
Upvotes: 6