Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to avoid the execution of a certain command?

Tags:

bash

I have to avoid the execution of a certain command in a bash script.
I thought to use a preexec trap to do so.

Let's say I want to avoid the command 'source' just for axample. What I did is basically the following:

#!/bin/bash

function preexec ()
{
    if test $( echo "$BASH_COMMAND" | cut -d " " -f1 ) == "source"
        then
            echo ">>> do not execute this"
        else
            echo ">>> execute this"

    fi
}
trap 'preexec' DEBUG

echo "start"
source "source.sh"
echo "go on"

exit 0

the idea works fine, but at this point I don't know how to avoid the execution of said command.
Any idea how to solve this?

like image 380
Luca Borrione Avatar asked Oct 21 '22 18:10

Luca Borrione


2 Answers

One workaround would be to define an alias for that command that does nothing and undefine it after the script has completed. The alias must be declared within the script itself for this to work:

alias source=:
## The actual script source here...
unalias source
like image 96
Costi Ciudatu Avatar answered Oct 27 '22 16:10

Costi Ciudatu


Redefine the source command by using a function called source.

Functions can be exported.

source() { builtin source /dev/null; return 0; }
source() { read < /dev/null; return 0; }
source() { :; return 0; }
export -f source
like image 21
caan Avatar answered Oct 27 '22 15:10

caan