2

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?

Community
  • 1
  • 1
Addison Crump
  • 666
  • 5
  • 19
  • As an aside, a proper process supervision system (runit, daemontools, supervisord, upstart, systemd, launchd, etc etc) could be set to auto-restart sshd whenever it dies from any cause, either `killall` or otherwise -- and as such tools can use `waitpid()`, they can do so much more efficiently than polling-based solutions. I'd suggest using one. :) – Charles Duffy Feb 08 '16 at 15:57
  • @CharlesDuffy Anything for efficiency. \o/ I'll make sure to look into it, thanks! – Addison Crump Feb 08 '16 at 16:02

1 Answers1

5

You want to intercept killall, so:

killall() {
  if [ "$1" = "sshd" ]; then
    echo "some warning message, and perhaps service sshd restart"
  else
    command killall "$@"
  fi
}
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • 2
    I'd suggest `command killall "$@"`, not `/path/to/real/killall "$@"`; that way you still get the regular PATH lookup, making the function that much more portable. – Charles Duffy Feb 08 '16 at 15:36
  • @CharlesDuffy: amended. I'm glad I've learned something. Thx. – Karoly Horvath Feb 08 '16 at 15:41
  • (Also see the second solution I offer in the answer to the linked question, which lets someone define a function for each subcommand they want to override -- for instance, `killall_sshd`; that way the definition of the wrapper for `killall` can be decoupled from the specific subcommands that are overridden). – Charles Duffy Feb 08 '16 at 16:00
  • What I learned today: you must put this in the _root_ .bashrc, because sudo is mean. :I – Addison Crump Feb 09 '16 at 12:05