【问题标题】:bash function work on terminal but not on .sh script file [duplicate]bash函数在终端上工作,但不在.sh脚本文件上[重复]
【发布时间】:2022-01-01 03:37:04
【问题描述】:

我正在学习 bash 功能,教程中包含基本功能。我的问题是,当我在终端上编写函数时它可以工作,但是当我将它写入 .sh 文件并尝试按其名称执行函数时,它不起作用

这是终点线:

输入:

$ hello_world () { echo ' hello world this is 2021' ;}

运行:

$ hello_world

hello world this is 2021

这是 hello_world.sh

$ vi hello_world2.sh

#!/bin/bash

hello_world2 () {
        echo ' hello world this is 2022' ;
}

当我尝试执行它时,我得到了这个错误:

$ hello_world2

zsh: command not found: hello_world2

【问题讨论】:

  • 你需要先source文件,定义函数。 . ./hello_world2.sh.
  • 你根本没有使用bash:你使用的是zsh
  • 我试过. ./hello_world2.sh 但没用。
  • hello_world2.sh 在哪里?你需要正确的路径;我以为它在当前工作目录中。
  • 好吧,您的函数在bashzsh 中都有效。因此,您可以获取文件(source hello_world2.sh. hello_world2.sh),然后调用您的函数(hello_world2)。对于给定的 zsh 或 bash 会话,您只需要 source 一次。请注意,如果此脚本确实用于采购,则不需要 shebang 行。

标签: bash zsh zshrc


【解决方案1】:

如果你尝试运行脚本,有两个问题:

  1. 您正在尝试执行不在PATH 上的脚本

  2. 您的脚本不可执行

解决办法:

# make the script executable
chmod u+x path/to/hello_world2.sh

# run the script
path/to/hello_world2.sh

如果您尝试在脚本中调用函数...

您的第一个示例之所以如此工作,是因为该函数已在 shell 中定义,因此只需搜索 $functions 数组即可找到该函数,然后运行其中的命令.

函数名,与包含该函数的文件名有很大不同。

如果您的目标是在脚本中运行该函数,那么您可以放弃上述步骤,改为执行以下操作:

# import the function into the current shell
source path/to/hello_world2.sh

# run the function
hello_world2

【讨论】:

  • 是不是也有“3.脚本定义了一个函数但实际上并没有调用它”?
猜你喜欢
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
  • 2019-12-23
  • 2015-03-13
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
相关资源
最近更新 更多