如何通过wget判断文件是否可解压并保留原文件名?
解决wget保留原文件名并判断zip格式解压的问题
先纠正你之前命令的错误
你写的命令有两个致命问题:
- Bash变量赋值不能加空格,
filename = wget ...这种写法语法错误,正确的赋值应该用filename=$(命令)的命令替换格式 - 直接把wget命令赋值给变量不会触发下载,wget的执行结果不会自动变成变量值,得通过捕获输出的方式获取文件名
完整解决方案
1. 让wget自动保留原文件名
使用wget的--content-disposition参数,它会解析服务器返回的Content-Disposition响应头,自动用头里指定的原始文件名保存文件,无需手动用-O指定:
wget --content-disposition http://www.vim.org/scripts/download_script.php?src_id=11834
2. 准确获取下载的文件名
如果需要在脚本里捕获文件名,可以通过wget的stderr输出提取(wget会打印Saving to: "文件名"的日志):
# 下载文件同时捕获文件名,--quiet关闭冗余输出 filename=$(wget --content-disposition --quiet --output-document=- http://www.vim.org/scripts/download_script.php?src_id=11834 2>&1 | grep -oP 'Saving to:.*"\K[^"]+')
这里用--output-document=-把文件内容输出到stdout,同时把stderr重定向到stdout,再用grep的正则提取引号内的文件名。
3. 判断文件是否可被unzip解压并执行操作
有两种可靠的判断方式:
方式一:用file命令检查MIME类型
if file --mime-type "$filename" | grep -q 'application/zip'; then unzip "$filename" else echo "错误:该文件不是zip格式,无法用unzip解压!" fi
方式二:直接用unzip测试文件有效性
这种方式更直接,能判断文件是否是可正常解压的zip:
if unzip -t "$filename" >/dev/null 2>&1; then echo "开始解压文件:$filename" unzip "$filename" else echo "错误:文件 $filename 不是有效的zip文件,无法解压!" fi
整合后的完整脚本
#!/bin/bash url="http://www.vim.org/scripts/download_script.php?src_id=11834" # 下载文件并获取原文件名 filename=$(wget --content-disposition --quiet --output-document=- "$url" 2>&1 | grep -oP 'Saving to:.*"\K[^"]+') # 判断并执行解压 if unzip -t "$filename" >/dev/null 2>&1; then echo "正在解压 $filename..." unzip "$filename" echo "解压完成!" else echo "❌ 错误:$filename 不是有效的zip文件,无法解压" fi
内容的提问来源于stack exchange,提问作者user19972954
相关产品推荐
相关产品推荐

