【问题标题】:Calling a function in Bash script [duplicate]在 Bash 脚本中调用函数 [重复]
【发布时间】:2016-09-22 06:11:44
【问题描述】:

我已经进行了足够多的搜索以找到这一点,但没有运气。我正在尝试编写一个 Bash 脚本,该脚本必须调用在其他地方定义的函数。

比如我有一个shell test.sh

#!/bin/bash

# Shell - test.sh

function1() {
   echo "Inside function 1"
}

function1
function2

exit 0

我有一个不同的文件,它有function2,

$ cat function2

function2() {
   echo "Inside function 2"
}

现在,当我运行 test.sh 时, (Q1)它如何知道在哪里可以找到 function2 ? (Q2) 没有显示函数 2 的回声输出

任何输入都会很棒。

您好,感谢您的回答。但是,令我惊讶的是,当我使用“$./test.sh”执行 shell 时,我得到了“Inside function 1”的输出。如果 shell 没有找到“function2”,它应该抛出一个错误,“找不到函数或其他东西”。我觉得以某种方式调用了该函数,但未显示该消息。

谢谢, 拉维

【问题讨论】:

  • source第一个文件中的第二个(你可以使用.作为source的快捷方式)
  • @DavidC.Rankin 反过来说,source 命令是. 命令的加长版本,但. 排在第一位。
  • 我总是把它倒过来,谢谢。我也弄错了鸡或蛋:)

标签: bash function shell scripting external


【解决方案1】:

继续评论,你sourcefile2file1,例如

#!/bin/bash

# Shell - test.sh

function1() {
    echo "Inside function 1"
}

if [ -r "file2" ]  ## make sure file2 is readable by file1
then
   . "file2"       ## source file2 in file1.
                   ## Yes the . is a command! Check 'help .'
else               ## otherwise show error and exit
    printf "error: file2 not readable by file1.\n" >&2
    exit 1
fi

function1
function2

exit 0

【讨论】:

  • 不确定是谁投了反对票。答案是正确的。
  • 这是新的秋季学期带来的少年投票小组的新成员。
【解决方案2】:

您必须在具有功能 1 的文件中导入具有完整路径的功能 2 的另一个文件。这样您就可以访问文件 2 的功能。

【讨论】:

  • 您好,感谢您的回答。但是,令我惊讶的是,当我使用“$./test.sh”执行 shell 时,我得到了“Inside function 1”的输出。如果 shell 没有找到“function2”,它应该抛出一个错误,“找不到函数或其他东西”。我觉得以某种方式调用了该函数,但未显示该消息。
猜你喜欢
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 2018-06-19
  • 1970-01-01
  • 2019-10-31
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
相关资源
最近更新 更多