Roc*_*uts 5 bash zsh sh shell-script global
假设我有这三个脚本文件:(所有 3 个都是可执行的)
bash-test.sh:
#!/bin/bash
HelloFromBash RocketNuts
Run Code Online (Sandbox Code Playgroud)
zsh-test.sh:
#!/bin/zsh
HelloFromZsh RocketNuts
Run Code Online (Sandbox Code Playgroud)
sh-test.sh:
#!/bin/sh
HelloFromSh RocketNuts
Run Code Online (Sandbox Code Playgroud)
从 shebang 中您可以看出,这些脚本分别由不同的 shell 执行,即bash
、zsh
、 和sh
。
这三个函数“HelloFromXyz”全部应该像这样定义:
function HelloFromBash { echo "Hello $1, this is Bash speaking" }
对于 zsh 和 sh 变体来说类似。
但问题是:我想在全局范围内定义这些函数,每个特定的 shell 都有一个函数。
如何或在哪里为这三个 shell 定义全局函数?这样,当我运行上面的三个脚本时,它们每个都可以使用该 shell 的特定全局函数。
如果有一种统一的方法可以同时为多个 shell 定义(或导出,或任何适当的术语)全局函数,那就更好了。但我相信情况并非如此,每个 shell 似乎都使用自己的机制。
(编辑)我知道无论是交互式 shell 和/或登录 shell 都可能存在差异。我希望该函数在所有情况下都可以在 shell 脚本中使用。所以我可以手动打开终端,并运行使用所述全局函数的脚本。或者我可以运行一个调用相同 shell 脚本的后台进程。
如果这需要在多个文件中定义或导出相同的函数,或者在另一个文件中包含/采购一个函数,我很想了解详细信息。
如果您想定义要在脚本中使用的函数“库”,请将它们写入您在使用该函数的脚本中“获取”的文件中:
“库”文件:
function the_function {
# whatever
}
Run Code Online (Sandbox Code Playgroud)
用法:
# include the library
source /path/to/the/library # You can also use ". /path/to/the/library"
# Or, of caller and library are in the same directory
source $(dirname "$0")/library
# Call the function in it
the_function arg1 arg2
Run Code Online (Sandbox Code Playgroud)
库文件不需要是可执行的,也不需要 shebang,因此如果编码充分,它可以由 bash 和 ksh(也许还有 zsh)使用。
归档时间: |
|
查看次数: |
4583 次 |
最近记录: |