在 shell 脚本 或交互式 shell 中,你可能会使用快捷 别名 或其他命令,却不知道你是在使用内置定义还是本地二进制文件。有一种简单的方法可以查明,即使用 bash 内置命令 type 和 command。
type 和 command 内置命令是什么?
shell 内置命令 type 和 command 都可以显示有关命令的信息,以及你的命令、bash 函数 或 bash 别名 在用作命令名称时将被如何解释。它们都是 POSIX 标准的一部分,尽管 bash 中的 type 内置命令提供了比 POSIX 定义更多的功能。
通过了解命令的类型,你可以确保 shell 脚本的正确行为。bash 中的命令类型将被标识为 alias、keyword、functions、builtin、file,对于未知类型则为空字符串。
command 内置命令还可以通过抑制 shell 查找来执行命令。这可以确保使用磁盘上的命令。
type: usage: type [-afptP] name [name ...]
command: usage: command [-pVv] command [arg ...]
如何查找命令的类型?
要找出 shell 命令的类型,你可以简单地使用 shell type 内置命令,语法为 type <命令名称>。带有 -V 选项的 bash command 内置命令将提供类似的详细输出。
[me@linux ~]$ type echo
echo is a shell builtin
[me@linux ~]$ command -V echo
echo is a shell builtin
在某些情况下,你可能希望在 shell 脚本中检查命令的类型,但解析 type 或 command 内置命令的详细输出并不理想。相反,使用 bash type 内置命令时,你可以使用 -t 选项。示例:type -t date。
或者,-a 选项提供命令的所有可能解释,包括 alias、builtin 和 function。
一个使用 bash type 内置命令的简单示例是配合 echo 命

1579

被折叠的 条评论
为什么被折叠?



