bash - 如何从脚本中检查函数是否存在于交互式 shell 中?

标签 bash non-interactive

我正在为一些包装器脚本编写安装文件,并将这些脚本映射到底层命令的完成。

在我的 .bash_profile 中,这将 git 的完成映射到 git_wrapper:

complete -F _git git_wrapper

在我的 setup.sh 中,以下内容不起作用,因为脚本不是交互式的(type _git 失败,因为 _git 在非交互式 shell 中不可用):

if type _git &>/dev/null && ! grep "complete.*_git git_wrapper" ~/.bash_profile &>/dev/null ; then
    echo "complete -F _git git_wrapper" >> ~/.bash_profile
fi

在 setup.sh 中,如何检查 _git 补全是否可用于交互式 shell?

最佳答案

From a script, how can I check if a function would exist in an interactive shell?

您可以通过运行交互式 shell(见下文)和 looking for it 来测试函数是否存在于交互式 shell 中。 .

请注意,“交互式”是此处定义的术语。一方面,如果 shell 在没有任何非选项参数且没有 -c 选项的情况下启动,并且其标准输入和错误都连接到终端,则它是“交互式”的。这很自然,但对您的目的来说不太有用。然而,另一方面,如果抛开所有其他考虑因素,如果使用 -i 选项启动 shell,它也是“交互式”的。您的脚本可以使用它在交互式子 shell 中执行测试,但也许更有用的是,您可以使用它使部分或全部脚本本身在交互式 shell 中运行。

关于bash - 如何从脚本中检查函数是否存在于交互式 shell 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38956791/

相关文章:

通过符号链接(symbolic link)访问时,bash 似乎忽略了 BASH_ENV

linux - bash: ./mybashfile.sh: 权限被拒绝

linux - cd/bash 在符号链接(symbolic link)上的行为

git - 为什么非交互式 rebase 上的 Git 提交后 Hook 未运行?

c - vim 的高效非交互使用

ssh - 如何以非交互方式进行远程 ssh

arrays - shell中输入的数字

linux - 将 bash 变量作为模式传递给 awk

bash - 从子进程调用 bash 函数

debugging - 避免 R 中的浏览器调用