如果您希望将二进制文件成为bash中的内置命令
方法1:创建bash函数
您可以通过在~/.bashrc
文件中创建bash函数来模拟这种行为:
function mycommand
{
/path/to/your/binary #plus arguments if any
}
export -f mycommand
使用mycommand
的方式与使用cd
的方式相同。
请查看此[ tldp文章 ],了解这种方法与实际内置命令的区别。
方法2:使用enable
我想通过创建一个用于查找阶乘的新内置命令来演示这一点。下面是我编写的代码:
#include <bash/config.h>
#if defined(HAVE_UNISTD_H)
#include <unistd.h>
#endif
#include <bash/shell.h>
#include <bash/builtins.h>
#include <stdio.h>
#include <stdlib.h>
unsigned long long factorial(unsigned long long x, unsigned long long amt)
{
if (x == 0)
return amt;
else
amt*=x;
return factorial(x-1, amt);
}
int factorial_wrapper(WORD_LIST* list)
{
char* ptr=NULL;
int num;
if (list == 0) {
builtin_usage();
fflush(stdout);
return (EX_USAGE);
}
else{
ptr=list->word->word;
num=atoi(ptr);
if (num>60){
builtin_usage();
fflush(stdout);
return (EX_USAGE);
}
printf("%llu\n",factorial(num,1));
fflush(stdout);
}
return (EXECUTION_SUCCESS);
}
char *factorial60_doc[] = {
"factorial60",
"Usage : factorial60 number",
"Description :",
"Gives the factorial of numbers upto 60",
(char *)NULL
};
struct builtin factorial60_struct = {
"factorial60",
factorial_wrapper,
BUILTIN_ENABLED,
factorial60_doc,
"Usage : factorial60 'number_upto_60'",
NULL
};
按照以下方式编译代码:
gcc -shared -fpic -o factorial.so factorial.c
将共享对象factorial.so复制到本地库位置,例如/usr/local/lib/mylib/
通过在~/.bashrc中添加以下内容(如果您希望其他用户使用新的内置命令,则可以添加到/etc/bash.bashrc中)来启用(持久化)新的内置命令:
enable -f /usr/local/lib/mylib/factorial.so factorial60 # You need to give the full path
完成!现在你已经有了新的内置命令,可以在新的shell会话中使用。
$ factorial60 24
10611558092380307456
$ factorial60
factorial60: usage: Usage : factorial60 'number_upto_60'
$ type -a factorial60
factorial60 is a shell builtin
$ factorial60 61
factorial60: usage: Usage : factorial60 'number_upto_60'
(感谢@chepner提醒)
方法三:重新编译Bash
通过重新编译Bash(有点“不太好”的方式!)添加功能 - [源代码在此] 。
参考资料:
enable
手册[这里]。
- WORD_LIST:内置函数总是给予一个类型为WORD_LIST的列表指针。如果内置函数实际上不需要任何选项,则必须在任何进一步处理之前调用no_options(list)并检查其返回值。如果返回值为非零值,则您的函数应立即返回EX_USAGE值。检查[此处]。
- 您需要安装
bash-builtins
库(我使用的是Ubuntu 12.04,实际软件包名称可能因发行版而异)以编译新的内置函数。
- 检查
builtin_usage
如何[定义]。
- 要使用enable命令,您的系统应支持动态加载。
- 在
enable
中,内置函数的名称(这里是factorial60)应与结构中给定的名称相匹配(注意factorial60_struct
),并且应将 builtin name 附加到结构中的_struct
后面。