“Aliasing” of Commands with Arguments [duplicate]

2019-01-20 15:40发布

问题:

This question already has an answer here:

  • Can I alias a subcommand? (shortening the output of `docker ps`) 1 answer

I know that some commands can be aliased through the shell, such as

alias mv="cp"

But I want to do something similar but with arguments (and yes, I have seen the other question, but my question is slightly different). Something similar to:

sshkill() {
  service sshd restart 
}
alias sshkill="killall sshd"

But this obviously doesn't work.

I wish to prevent users from directly killing the sshd (at least by accident) and make it restart (this is for a server where this has happened more than once). So, rather than aliasing, is there a way to prevent the command killall sshd from being executed and rather executing service sshd restart instead?

回答1:

You want to intercept killall, so:

killall() {
  if [ "$1" = "sshd" ]; then
    echo "some warning message, and perhaps service sshd restart"
  else
    command killall "$@"
  fi
}


标签: bash alias