Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在bash脚本中,如何运行外部定义的bash函数?_Bash - Fatal编程技术网

在bash脚本中,如何运行外部定义的bash函数?

在bash脚本中,如何运行外部定义的bash函数?,bash,Bash,例如,以下命令不起作用。我想知道如何解决这个问题,谢谢 [liuke@liuke-mbp ~]$ function showxx() { echo xx; } [liuke@liuke-mbp ~]$ showxx xx [liuke@liuke-mbp ~]$ cat a.bash #!/bin/bash showxx [liuke@liuke-mbp ~]$ ./a.bash ./a.bash: line 2: showxx: command not found 您必须定义要显示在本地

例如,以下命令不起作用。我想知道如何解决这个问题,谢谢

[liuke@liuke-mbp ~]$ function showxx() { echo xx; }
[liuke@liuke-mbp ~]$ showxx
xx
[liuke@liuke-mbp ~]$ cat a.bash 
#!/bin/bash
showxx
[liuke@liuke-mbp ~]$ ./a.bash 
./a.bash: line 2: showxx: command not found

您必须定义要显示在本地进程“范围”中的函数

当您在命令行中输入一个函数时,它现在在终端shell的bash副本中“活动”

启动脚本时,只有标记为
export
的变量才能在作为终端子项运行的bash的新副本中可见。(我们现在不会进入导出;-)

要在脚本中获取函数,必须在脚本中定义它

cat a.bash
#!/bin/bash
function showxx() { echo xx; }
showxx
或者您可以将函数放在一个单独的文件中并“源”它(使用“.”),这样它就好像它在文件中一样,即

 cat    showxx.bfn
 function showxx() { echo xx; }

 cat a.bash
 . showxx.bfn
 showxx
扩展名.bfn就是我用来帮助记录文件内部内容的东西,比如bfn='bash function'

“.”是源命令

我希望这有帮助


另外,当您看起来是新用户时,如果您得到一个有助于您的答案,请记住将其标记为已接受,并/或给它一个+(或-)作为有用的答案。

您需要导出您的函数。您可以在使用
set-a
创建时导出所有函数(我的首选项),也可以使用
export-f showxx
单独导出函数。这两种方法都会将脚本放入环境中,子shell将能够拾取它们。

使用前面的点和空格调用脚本

。a、 bash