【发布时间】: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在哪里?你需要正确的路径;我以为它在当前工作目录中。 -
好吧,您的函数在
bash和zsh中都有效。因此,您可以获取文件(source hello_world2.sh或. hello_world2.sh),然后调用您的函数(hello_world2)。对于给定的 zsh 或 bash 会话,您只需要 source 一次。请注意,如果此脚本确实用于采购,则不需要 shebang 行。