Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept and prevent command from running in bash

Tags:

bash

Is it possible to intercept all commands in bash and the prevent some of the from executing? Like with 'trap' command, only disallow to execute the command further.

I'm a web developer and currently working on a small project/script that would help a web developer in daily life by adding different aliases dynamically. For instance, as a web developer, on Ubuntu one usually hosts all projects in /var/www/ structure, thus it is possible to alias those folders in that (/var/www) folder. I want to improve my script a bit and add aliases to projects depending on which framework they're built. If it's Magento 2, then by running setup:upgrade it should run "bin/magento setup:upgrade". I've tried trap 'something' DEBUG, but it is not possible to prevent the previous command, as far as I know. Thanks!

like image 870
matiss.andersons Avatar asked Oct 24 '25 15:10

matiss.andersons


1 Answers

Yes, it is possible. trap ... DEBUG is a good start and if you want to prevent some commands, you must associate it with shopt -s extdebug. Then, if you return from the trap with a non-zero status, the command will not be executed.

$ trap 'if [[ "$BASH_COMMAND" == "echo "* ]]; then printf "[%s]\n" ${BASH_COMMAND#echo}; false; fi' DEBUG
$ set -T              # Necessary for subshells and functions
$ shopt -s extdebug
$ echo foo bar
[foo]
[bar]
$ trap - DEBUG
$ echo foo bar
foo bar
like image 147
xhienne Avatar answered Oct 27 '25 11:10

xhienne