overriding user defined functions with the same name as system commands

14

2

This function exists in one of my users' ~/.bashrc:

function rm()
{
        ls $*
        echo "rm?"
        read ans
        if [ "$ans" == 'y' ]; then
                /bin/rm $*
        fi
}

In my ksh script that users are required to run, I have a line like this:

[[ "$KEEP" = "" ]] && \rm $FILE

While the backslash escapes user-defined aliases, it does not stop the script from running user defined functions with the same name. As a result, my user's rm() function is called instead of the system function.

I found this superuser question question & response, but the resolution only applies to a builtin function, not a system command.

What's the best to enforce the rm command from being called, and not an alias or function? Must I specify the full path to rm and every system command that I want to ensure is executed correctly? Is there a better way?

acm

Posted 2012-09-13T17:10:15.697

Reputation: 243

Answers

13

You can use command to circumvent the normal bash function lookup.

command rm

Non-destructive example:

$ alias which='which -s'
$ function which { echo "which $@?" ; }
$ which which
which -s which?
$ command which which
/usr/bin/which

Alternatively, call it using env (executing the first program with the given name on the $PATH, or by specifying the full path.

/usr/bin/env rm
/bin/rm

Daniel Beck

Posted 2012-09-13T17:10:15.697

Reputation: 98 421

thanks, "command" is exactly what I'm looking for. It seems kind of obtuse to have to use for every system command executed though. I guess the only sure fire way to ensure you're running the system command is to specify the whole path. However, you're banking on the commands being in the same path across different distros at with that approach. – acm – 2012-09-17T18:07:10.293

@acm As I wrote, you can also go the env route. Additionally, you can determine each tool's location once and store it in a variable, e.g. RM=$( /usr/bin/env which rm ); [much more code]; $RM some_file;. You could also change how your script is executed. Usually, functions and aliases aren't inherited, otherwise they'd break scripts all the time. – Daniel Beck – 2012-09-17T18:16:08.623