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

如何在TypeScript中调用bash脚本?现有实现无法生效求解决方案

解决步骤

  1. 补全脚本执行权限与路径校验
  • 先给sh脚本添加可执行权限,终端执行:chmod +x 你的脚本文件路径
  • 不要用相对路径指定脚本位置,相对路径是相对于Node进程启动目录,很容易匹配错误。用path.resolve生成绝对路径,示例:
import * as path from 'path'
// __dirname为当前TS文件所在目录,替换为你的脚本相对当前文件的路径
const scriptPath = path.resolve(__dirname, './test.sh')

如果你的TS用的是ESModule模块规范(tsconfig中module设为ESNext/ES2022等),不支持__dirname,改用以下方式拿路径:

const scriptPath = new URL('./test.sh', import.meta.url).pathname
  1. 修正exec调用方式,补全错误与输出监听
    你目前的写法没有监听exec的异步回调,就算脚本执行报错、输出内容你也看不到。正确写法参考:
import { exec } from 'child_process'

exec(`bash ${scriptPath}`, (error, stdout, stderr) => {
  // 捕获执行错误,比如找不到文件、无权限等
  if (error) {
    console.error('执行失败:', error)
    return
  }
  // 捕获脚本自身的错误输出
  if (stderr) {
    console.error('脚本错误输出:', stderr)
    return
  }
  // 打印脚本的正常输出,你echo的'works'会在这里打印
  console.log('脚本执行成功,输出:', stdout)
})
  1. 环境适配校验
    如果是Windows系统运行,默认没有bash执行环境,需要提前安装WSL、Git Bash,或者把执行命令换成对应适配的写法。
    另外要确保你已经安装了Node的类型依赖,避免TS编译报错:npm i @types/node -D

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:27:03