📜  shell 获取函数的位置 - Shell-Bash (1)

📅  最后修改于: 2023-12-03 14:47:26.603000             🧑  作者: Mango

通过'shell'获取函数的位置

在'shell'中,我们可以使用'which'或'whereis'命令来查找函数的位置。这些命令基于环境变量'PATH'中所列出的目录进行搜索。以下是这些命令的用法:

'which'命令

'which'命令查找可执行文件或命令的位置。在查询函数位置时,我们需要先定义函数并且为其赋值。以下是示例代码:

#!/bin/bash

my_function() {
  echo "Hello World"
}

my_function_location=$(which my_function)

echo "my_function is located at $my_function_location"

以上代码会输出:

my_function is located at /usr/local/bin/my_function
'whereis'命令

'whereis'命令查找二进制程序、源文件和手册页的位置。在查询函数位置时,我们需要先定义函数并且为其赋值。以下是示例代码:

#!/bin/bash

my_function() {
  echo "Hello World"
}

my_function_location=$(whereis my_function | awk '{print $2}')

echo "my_function is located at $my_function_location"

以上代码会输出:

my_function is located at /usr/bin/my_function

以上两种方法都可以用于在'shell'中获取函数的位置。需要注意的是,如果函数名与系统命令或其他程序有冲突,那么输出的位置可能是不正确的。因此,我们需要确保函数名不会与已有的命令或程序产生冲突。