如何防止获取 bash 脚本的一部分?

How to prevent sourcing a part of a bash script?

我有一个 shell 脚本,其语法兼容 bashzsh,除了具有 zsh 特定语法的部分。如果来自 bash 则抛出语法错误 使用 bash.

时是否有一种简单的方法来逃避此类部分

该脚本是一个 bash 函数,可获取目录中的所有文件。它在 zsh 形式下工作正常(并且与问题无关)

#!/usr/bin/env bash

shell=$(ps -p $$ -oargs=)

if [ $shell = "bash" ]; then
    for f in ~/.functions.d/*.sh; do source $f; done
elif [ $shell = "zsh" ]; then
    for f (~/.functions.d/**/*.sh) source $f
fi

错误是由第 7 行产生的,当在 bash

中获取它时

相关链接

问题是整个 if/elif/else 语句被作为一个单元来分析,所以它不能包含无效语法。

您可以做的是在执行特定于 zsh 的代码之前退出源脚本:

shell=$(ps -p $$ -oargs=)

if [ $shell = "bash" ]; then
    for f in ~/.functions.d/*.sh; do source $f; done
    return
fi

if [ $shell = "zsh" ]; then
    for f (~/.functions.d/**/*.sh) source $f
fi

但是,更通用的解决方案是将 bash 特定代码和 zsh 特定代码提取到单独的脚本中。

shell=$(ps -p $$ -oargs=)

if [ $shell = "bash" ]; then
    source load_functions.bash
fi

if [ $shell = "zsh" ]; then
    source load_functions.zsh
fi

load_functions.bash 将包含第一个 for 循环,而 load_functions.zsh 将包含第二个循环。

我会做一个

if [[ -n ${BASH_VERSION:-} ]]
then
   : we are in bash
else
   : we are not
fi

变量 BASH_VERSION 保证由 bash 设置,除非您明确(恶意)篡改此变量,否则应该没问题。