首页 > 解决方案 > 如何在 if 条件下调用带有参数的外部 bash 函数

问题描述

我试图在我的主脚本中以 if 条件调用外部 bash 脚本。外部脚本 IsArchive 的代码:

#!/bin/bash
STR="$1"

if [[ "$STR" ==  *".zip"* ]] || [[ "$STR" ==  *".iso"* ]] || [[ "$STR" ==  *".tar.gxz"* ]] || [[ "$STR" ==  *".tar.gx"* ]] || [[ "$STR" ==  *".tar.bz2"* ]] || \
   [[ "$STR" ==  *".tar.gz"* ]] || [[ "$STR" ==  *".tar.xz"* ]] || [[ "$STR" ==  *".tgz"* ]] || [[ "$STR" ==  *".tbz2"* ]]
then
        return 0
else 
        return 1
fi

我尝试在我的主脚本中调用它:

elif [[ $Option = "2" ]]
then
                if IsArchive "$SourcePath";
                then
                        less -1Ras "$SourcePath" | tee "$OutputFilePath"

                #if file is not an archive
                else
                        ls -1Rasl "$SourcePath" | tee "$OutputFilePath"
                fi

当我执行主脚本时,我收到错误:./script: line 61: IsArchive: command not found

标签: bashif-statement

解决方案


您只需要确保脚本在您的 PATH 中。要么,要么用完整路径或相对路径引用它。也许你只需要写:

if ./IsArchive "$SourcePath"; then ...

但是有几个问题IsArchive。您不能return从函数中除外,因此您可能想要使用exit 0andexit 1而不是return. 您可能不想将名称视为foo.zipadeedoodah存档,但*".zip"*会匹配它,因此您可能应该删除尾随的*. 用 case 语句编写它会更简单:

#!/bin/bash

case "$1" in
*.zip|*.iso|*.tar.gxz|*.tar.gx|*.tar.bz2| \
*.tar.gz|*.tar.xz|*.tgz|*.tbz2) exit 0;;
*) exit 1;;
esac

推荐阅读