在别名中设置错误的退出代码

sym*_*ean 0 bash

我正在向 .bashrc 添加一些别名,以阻止人们使用标准命令,因为在这些命令中需要更复杂的过程才能实现所需的结果。但是,如果从脚本调用别名,我该如何设置退出代码?理想情况下不会产生像“没有这样的文件或目录”这样的虚假错误消息(我确实找到了这个,但肯定有更干净的方法?)

例如

 alias useradd='echo "Nope....you should be using the custom script."'
Run Code Online (Sandbox Code Playgroud)

应该导致......

 # useradd newuser
 Nope....you should be using the custom script.
 # echo $?
 -1
 #
Run Code Online (Sandbox Code Playgroud)

jes*_*e_b 6

您应该使用函数而不是别名。

useradd () {
  echo "Nope....you should be using the custom script." >&2
  return 2
}
Run Code Online (Sandbox Code Playgroud)

请参阅在 Bash 中,何时使用别名、何时编写脚本以及何时编写函数?有关别名限制和函数用途的更多信息。

另请注意,无论您使用函数还是别名,您的用户都可以通过使用command内置函数或简单地转义命令名称来绕过它们,例如:

\useradd ...
Run Code Online (Sandbox Code Playgroud)