You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure DevOps中BASH脚本查找.zip文件并赋值变量遇阻

问题解决:Azure DevOps中unzip无法找到Zip文件的问题

问题描述

  • 已完成操作:
    1. 在Azure DevOps中发布工件
    2. 尝试从工件中找到有效.zip文件并赋值给变量,用于后续CURL请求传递
  • 问题现象:/home/vsts/work/1/a/Package目录下存在.zip文件,脚本能识别并输出文件名,但执行unzip时提示无法找到或打开该文件,无法查看文件内容。

所用代码

- task: Bash@3
inputs:
targetType: 'inline'
script: |
        currdir="$(Build.ArtifactStagingDirectory)/Package"

        if [ -e "$currdir"/*.zip ]; then
        echo "There are zip files with .zip extension inside '$currdir'"
        fi

        zip_f=("$currdir"/*.zip)
        echo $zip_f
        if [ ${#zip_f[@]} -eq 0 ]; then
           echo "No Zip File"
        fi
        z=${zip_f[0]}
        zipfilename=$(basename "$z")
        unzip -l $zipfilename | awk '{print $1 "\t"  $4}' | tail -n+4 | head -n-2

问题原因

脚本中使用basename "$z"仅提取了Zip文件的文件名,未保留完整路径。执行unzip命令时,当前工作目录并非$currdir,系统会在当前工作目录下查找该文件名,导致无法定位到目标文件。

解决方案

有两种可行的修正方式:

方式一:使用完整路径执行unzip

直接使用Zip文件的完整路径$z执行unzip,无需单独提取文件名:

unzip -l "$z" | awk '{print $1 "\t"  $4}' | tail -n+4 | head -n-2

方式二:切换到目标目录后执行unzip

在提取文件名前,先切换到$currdir目录:

currdir="$(Build.ArtifactStagingDirectory)/Package"
cd "$currdir"

if [ -e ./*.zip ]; then
echo "There are zip files with .zip extension inside '$currdir'"
fi

zip_f=(./*.zip)
echo $zip_f
if [ ${#zip_f[@]} -eq 0 ]; then
   echo "No Zip File"
fi
z=${zip_f[0]}
zipfilename=$(basename "$z")
unzip -l "$zipfilename" | awk '{print $1 "\t"  $4}' | tail -n+4 | head -n-2

额外优化:处理多Zip文件场景

如果目录下可能存在多个Zip文件,建议增加判断逻辑避免后续操作出错:

if [ ${#zip_f[@]} -gt 1 ]; then
   echo "Warning: Multiple zip files found, using the first one: ${zip_f[0]}"
fi

内容的提问来源于stack exchange,提问作者Subrajit Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 15:14:56