Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to execute shell commands inside handler? #195

Open
nikitavoloboev opened this issue Mar 2, 2023 · 5 comments
Open

How to execute shell commands inside handler? #195

nikitavoloboev opened this issue Mar 2, 2023 · 5 comments

Comments

@nikitavoloboev
Copy link

nikitavoloboev commented Mar 2, 2023

I tried doing this:

import { command, optional, positional, run, string } from "cmd-ts"
import { execa } from "execa"

const cmd = command({
  name: "gitty",
  description: "automate git",
  version: "0.0.1",
  args: {
    query: positional({ type: optional(string), displayName: "query" }),
  },
  handler: async (args) => {
      const { stdout } = await execa("echo", ["unicorns"])
      console.log(stdout)

  },
})

run(cmd, process.argv.slice(2))

But then if you try run it, you won't get echo unicorns as output.

If you run below code outside the handler:

      const { stdout } = await execa("echo", ["unicorns"])
      console.log(stdout)

It works as expected. Not sure why that happens or how to fix.

@nikitavoloboev
Copy link
Author

repo where I am using cmd-ts: https://github.com/nikitavoloboev/gitty

code I want to make work is here

@Schniz
Copy link
Owner

Schniz commented Mar 2, 2023

What’s the console output then?

@nikitavoloboev
Copy link
Author

nikitavoloboev commented Mar 2, 2023

It's empty.

image

@Schniz
Copy link
Owner

Schniz commented Mar 4, 2023

Very suspicious. I hope I will have some time to take a look. You are more than welcome to fork and add a test.

@7frank
Copy link

7frank commented Aug 16, 2024

I think i might have a similar problem using bun shell instead of "execa"

running

const pwd= await $`pwd`.text()
console.log(pwd)

inside a "handler" will simply terminate the script and not output anything

A workaround is using a custom script.

function execShellCommand(cmd:string):Promise<string> {
  const exec = require('child_process').exec;
  return new Promise((resolve, reject) => {
   exec(cmd, (error:unknown, stdout:string, stderr:string) => {
    if (error) {
     console.warn(error);
    }
    resolve(stdout? stdout : stderr);
   });
  });
 }
const pwd=await execShellCommand(`pwd`)
console.log(pwd)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants