3

In bash I can do:

#!/bin/bash
validate() {
    if [[ "$BASH_COMMAND" == whoami ]]; then
        return 1
    else
        return 0
    fi
}
set -T
trap 'validate' DEBUG
shopt -s extdebug

so that if I run whoami nothing happens.

How can I achieve the same in zsh ? I've looked at preexec but I couldn't find much information in the documentation

5
  • 2
    Would it not be easier (in bash too) to use whoami () { false; }?
    – Kusalananda
    Feb 22 at 13:14
  • @Kusalananda, actually in zsh (and most Bourne-like shells, bash being an exception), whoami() false would be enough. In Korn-like shells including bash and zsh, you can also do whoami() ((0)) Feb 22 at 13:53
  • 1
    Related How to display text for non-interactive login shell. What is with people wanting to hijack whoami these days? Feb 22 at 14:28
  • (even whoami()(()) or in zsh: whoami(){!}) Feb 22 at 14:45
  • @StéphaneChazelas whoami was only for illustration purposes. it was the first command I could think of
    – Foo
    Feb 22 at 17:15

1 Answer 1

5

You can also use the DEBUG trap to skip a command in zsh, but the mechanism to indicate skipping is different: you need to set the err_exit option.

function validate {
    if [[ "$ZSH_DEBUG_CMD" == whoami ]]; then
        setopt err_exit
    fi
}
trap 'validate' DEBUG
2
  • 1
    Note that one can always work around it by running \whoami or "whoami" or command whoami or env whoami or sh -c whoami or /usr/bin/whoami... Feb 22 at 13:55
  • 1
    @StéphaneChazelas Or $(base64 -d <<<d2hvYW1pCg==). A blacklist can't be a security measure, and even a whitelist is hard. Feb 22 at 13:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .