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

如何在Visual Studio Code中以当前行/代码块为参数运行Shell脚本

在VS Code中用选中内容/当前行作为参数运行Shell脚本

当然可以实现类似Python插件的功能,直接用VS Code内置的任务(Tasks)和变量就能搞定,不需要额外装扩展,步骤如下:

1. 配置任务文件(tasks.json)

打开命令面板(Ctrl+Shift+P / Cmd+Shift+P),输入 Tasks: Configure Task,选择「Create tasks.json file from template」,再选「Others」,会自动生成.vscode/tasks.json文件。

把文件内容替换成下面的配置(记得替换/path/to/your/script.sh为你实际的Shell脚本路径):

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Run Selected Text as Script Arg",
      "type": "shell",
      "command": "/path/to/your/script.sh \"${selectedText}\"",
      "problemMatcher": [],
      "presentation": {
        "reveal": "always",
        "panel": "shared"
      }
    },
    {
      "label": "Run Current Line as Script Arg",
      "type": "shell",
      "command": "/path/to/your/script.sh \"${lineText}\"",
      "problemMatcher": [],
      "presentation": {
        "reveal": "always",
        "panel": "shared"
      }
    }
  ]
}

配置说明:

  • ${selectedText}:代表你在编辑器中选中的文本内容,用双引号包裹可以避免空格、特殊字符导致参数被拆分。
  • ${lineText}:代表光标当前所在行的完整文本。
  • presentation字段设置运行时自动打开终端,且复用同一个终端面板,和Python插件的体验一致。

2. 绑定快捷键(可选)

如果不想每次都通过命令面板找任务,可以给任务绑定快捷键:
打开命令面板,输入 Preferences: Open Keyboard Shortcuts (JSON),在keybindings.json里添加:

{
  "key": "ctrl+shift+r",
  "command": "workbench.action.tasks.runTask",
  "args": "Run Selected Text as Script Arg",
  "when": "editorTextFocus"
},
{
  "key": "ctrl+shift+l",
  "command": "workbench.action.tasks.runTask",
  "args": "Run Current Line as Script Arg",
  "when": "editorTextFocus"
}

这样:

  • 选中代码块后按Ctrl+Shift+R(Mac是Cmd+Shift+R),就会把选中内容作为参数传给你的Shell脚本。
  • 光标放在某一行按Ctrl+Shift+L(Mac是Cmd+Shift+L),就会把当前行作为参数运行脚本。

3. 注意事项

  • 如果你的脚本需要处理多行文本,${selectedText}会保留原换行符,脚本里可以直接读取处理。
  • 如果文本里包含双引号,需要在脚本里做转义处理,或者把command里的双引号换成单引号(但要注意单引号在Shell里不会转义内部字符)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:15:15