skip to Main Content

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!

2

Answers


  1. You can veto commands by abusing command_not_found_handle:

    # Save the PATH
    realpath="$PATH"
    # Set a PATH without commands (weirdly can't be empty)
    PATH="/"
    
    command_not_found_handle() (
      if [[ "$1" == *d* ]]
      then
        echo "Sorry, no commands with 'd' allowed" >&2
        return 1
      else
        PATH="$realpath" 
        unset command_not_found_handle
        "$@"
      fi
    )
    

    With this in your .bashrc, you can run ls and chown but not find or chmod. Note that it does not affect functions or builtins.

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search