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

使用Dart Shell.run执行tar命令时./*路径报错求助

解决Dart Shell.run执行tar命令时./*通配符失效问题

问题原因

终端执行命令时,./*通配符由shell(如bash)解析为当前目录下的所有非隐藏文件/目录后再传递给tar;但Dart的Shell.run会直接将./*作为字面量参数传给tar,而tar本身不具备解析shell通配符的能力,因此会报错找不到./*这个文件。

解决方案

方案1:通过bash执行命令,让shell解析通配符

将命令包裹在bash -c中,借助bash完成通配符解析:

final tarResult = await shell.clone(verbose: true, commandVerbose: true, commentVerbose: true).run(
  'bash -c "tar --exclude=example --exclude=test --exclude=$tarName -czvf $tarName ./*"',
);

注意:如果$tarName包含特殊字符,需要额外转义以避免引号冲突。

方案2:直接传递当前目录(替代./*)

tar支持将目录作为参数,若不需要排除隐藏文件,可直接用.替代./*,tar会打包当前目录下所有内容(包括隐藏文件):

final tarResult = await shell.clone(verbose: true, commandVerbose: true, commentVerbose: true).run(
  'tar --exclude=example --exclude=test --exclude=$tarName -czvf $tarName .',
);

方案3:用Dart API获取文件列表,显式传递参数

通过Dart文件系统API获取当前目录下的非隐藏文件/目录,将路径作为参数传给tar,彻底规避通配符解析问题:

import 'dart:io';

// 获取当前目录下的非隐藏文件/目录
final dir = Directory('.');
final entities = await dir.list(recursive: false)
    .where((entity) => !entity.path.startsWith('./.'))
    .map((e) => e.path)
    .toList();

// 构造tar命令参数
final args = [
  '--exclude=example',
  '--exclude=test',
  '--exclude=$tarName',
  '-czvf',
  tarName,
  ...entities,
];

// 执行命令
final tarResult = await shell.clone(verbose: true, commandVerbose: true, commentVerbose: true)
    .runExecutable('tar', args);

验证建议

优先测试方案2(若符合需求),操作最简单;如果需要严格匹配./*的行为(排除隐藏文件),则选择方案1或方案3。

内容的提问来源于stack exchange,提问作者Fabio S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:55:27