我目前正在使用鱼壳。由于我经常使用fish
, zsh
, bash
,我如何在其中一个中定义一个可用于所有 shell 的函数?我必须在 中定义它们.profile
吗?
一旦我离开终端并在之后重新使用它,我得到:
您可以在~/.*rc
您使用的每个 shell的文件中定义函数。或者,您可以为该函数和要在所有 shell 中使用的其他 shell 函数创建一个新文件……例如……
nano shell-functions
Run Code Online (Sandbox Code Playgroud)
我在文件中定义了我的函数...
hi() { echo "How are you $1?" ; }
Run Code Online (Sandbox Code Playgroud)
保存并退出,然后我编辑我的~/.bashrc
和~/.zshrc
并在每个人的末尾添加以下行:
source shell-functions
Run Code Online (Sandbox Code Playgroud)
要不就
. shell-functions
Run Code Online (Sandbox Code Playgroud)
它做同样的事情。
编辑~/.*rc
完我的文件后,我打开一个新的 shell,该功能可用:
$ bash
$ hi zanna
how are you zanna ?
$ zsh
% hi zanna
how are you zanna ?
Run Code Online (Sandbox Code Playgroud)
该source
命令在当前 shell 中读取文件并从它们执行命令(与./script
在新 shell 中运行脚本时不同)。在这种情况下,您想要为正在打开的 shell 定义一个函数,以便您希望source
包含它的文件在 shell 中可用。如果您查看您~/.profile
的配置文件,您可以看到一个配置文件的示例,如下所示:
# if running bash
if [ -n "$BASH_VERSION" ]; then
# include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
Run Code Online (Sandbox Code Playgroud)
所以是Ubuntu 中的默认~/.profile
源~/.bashrc
。您还可以source
通过创建一个文件来进行测试,让我们称之为file1
,其中包含一些命令,例如(对于 bash)PS1='I messed up my prompt '
保存,退出,然后在 shell 类型中source file1
,您将看到效果(打开一个新的 shell(例如 typebash
或 open一个新的终端窗口),一切都会恢复正常)...