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

如何在tar命令-T选项的文件中正确使用正则表达式

使用tar --files-from选项时通配符失效的问题解决

问题场景

项目目录结构如下:

testproj
|
|__testapp
|  |
|  |__src
|  |  |
|  |  |__test1.js
|  |  |__test2.js
|  |  |__test3.js
|  |  |
|  |__static
|  |  |
|  |  |__main.js
|  |  |
|  |__templates
|  |  |
|  |  |__main.html
|  |  |
|  |  test1.py
|  |  test2.py
|  |  test3.py
|  |  db1.db
|  |  db2.db
|  |  |
|  tarlists.txt
|  test.sh

tarlists.txt文件内容:

testapp/static
testapp/templates
testapp/*.py

在testproj目录下执行归档命令时出现错误:

$ tar czvf testproj.tar.gz -T tarlists.txt
testapp/static/
testapp/static/main.js
testapp/templates/
testapp/templates/main.html
tar: testapp/*.py: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors

但直接在命令行指定通配符却能正常归档:

$ tar czvf testproj.tar.gz testapp/*.py
testapp/test1.py
testapp/test2.py
testapp/test3.py

疑问:tarlists.txt中的通配符写法是否有误?如何在该文件中正确使用通配符?

原因分析

核心问题在于Shell解析时机的差异:

  • 直接在命令行输入testapp/*.py时,是Shell先把通配符展开成具体的testapp/test1.py、testapp/test2.py等文件名,再传递给tar命令;
  • 但使用-T/--files-from选项时,tar会直接读取文件中的每一行作为字面量文件名,不会触发Shell的通配符解析,所以它会去查找名为testapp/*.py的文件,自然找不到。

解决方法

方法1:写入具体文件名

如果.py文件数量不多且固定,直接把具体文件名写入tarlists.txt:

testapp/static
testapp/templates
testapp/test1.py
testapp/test2.py
testapp/test3.py

之后执行原tar命令即可正常归档。

方法2:让tar自行解析通配符

GNU tar提供了--wildcards选项,允许它自己解析文件列表中的通配符。执行命令时加上该选项:

$ tar czvf testproj.tar.gz --wildcards -T tarlists.txt

这样tar会自动匹配testapp/*.py对应的文件,完成归档。

方法3:通过Shell生成文件列表

如果需要动态匹配文件,可以用Shell命令把展开后的文件名写入tarlists.txt:

# 先清空或创建文件
$ echo "testapp/static" > tarlists.txt
$ echo "testapp/templates" >> tarlists.txt
# 把匹配到的.py文件追加到列表中
$ ls testapp/*.py >> tarlists.txt

之后再执行原tar命令就能正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:15:42