bash - 如何在 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
解决方案
您只需要确保脚本在您的 PATH 中。要么,要么用完整路径或相对路径引用它。也许你只需要写:
if ./IsArchive "$SourcePath"; then ...
但是有几个问题IsArchive
。您不能return
从函数中除外,因此您可能想要使用exit 0
andexit 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
推荐阅读
- facebook - Facebook API 发送消息:如何发送链接
- javascript - Cesium实时使用本地时间而不是UTC
- c# - 如果我从其他 UC 调用代码,WPF 绑定问题
- google-apps-script - 为什么这个脚本不收集所有的 gmail?
- python - 为什么当 k 是迭代器时 zip(*k) 不能工作?
- java - Spring Boot 优雅关闭
- php - 使用 REST Web 服务将图像上传到资源
- reactjs - 使用 react-vis 在 x 轴中以(MM-DD)格式显示日期
- symfony - Symfony 表单查询生成器
- reactjs - 如何修复“初始化时 DeltaPatcher 应接收基本 Bundle”?