【问题标题】:How to access function in bashrc at new terminal如何在新终端访问 bashrc 中的函数
【发布时间】:2017-07-06 01:21:27
【问题描述】:

我像这样在.bashrc 中创建了一个函数;

 #!/bin/bash
 function test() { ls; }
 export -f test

并像这样在新终端中调用它;

$ test

结果是test: command not found

我在访问.bashrc 中的函数时做错了什么?

【问题讨论】:

  • 在调用函数之前你有没有运行source .bashrc
  • 很有趣,因为test 存在于任何系统上。
  • 你的.bashrc文件是在哪里写的?而且,你真的在​​运行bash吗?
  • @jm666 test 不是函数的真实名称。我在这里编的,我讨厌 foo 和 bar
  • @codeforester 是的,我试过了,没有任何改变

标签: bash function shell unix command


【解决方案1】:

直到.bashrc 被显式地或在非登录交互式shell 启动时才定义该函数。如果您的终端启动了登录 shell,则该文件将不会被获取。

你不需要导出函数。

【讨论】:

  • 你的意思是,据我所知,我需要运行source .bashrc。我这样做了,但出现了同样的结果。
  • 您需要在您的问题中加入一些实际事实:您正在采购的 exact 文件,以及您正在运行但不起作用的命令。
【解决方案2】:

您可能希望在您的主目录中创建一个“.function”文件并将其源代码到您的 .bashrc 中。

之前:如下所示,它不起作用。

%_Host@User> add 2 3
bash: add: command not found...

在 $HOME/.function 中定义一个函数

%_Host@User> cat ~/.function
add ()
{
        echo "$1 + $2" | bc
}

这是我在 $HOME/.bashrc 中采购所有功能的方式

%_Host@User> cat ~/.bashrc|grep source|grep func
        source $HOME/.function
%_Host@User>

您可能需要 bash 或重新登录,或者在提示符下键入 bash,它应该可以工作。

现在可以了:

%_Host@User> add 2 3
5
%_Host@User>

请试一试。谢谢。

【讨论】:

    猜你喜欢
    • 2019-11-05
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    相关资源
    最近更新 更多