Home > Blockchain >  unable to use git echo commands in golang
unable to use git echo commands in golang

Time:06-10

I'm unable to echo a string into a new file , it works if I use a filename with some extension(.txt, .go, etc) but it doesn't work when I just use a filename without file extension

I want the below bash commands to be executed in golang

echo "testDir/*"> .git/info/sparse-checkout
git checkout <Branch Name>

code snippet:

// Remove the redirect from command
cmd := exec.Command("echo", "testDir/*")

// Make test file
testFile, err := os.Create(".git/info/sparse-checkout")
if err != nil {
    panic(err)
}
defer testFile.Close()

// Redirect the output here (this is the key part)
cmd.Stdout = testFile

err = cmd.Start(); if err != nil {
    panic(err)
}
cmd.Wait()

branchCmd := exec.Command("git checkout <Branch Name>")

CodePudding user response:

The echo command just print the list of arguments. The command interpreter (shell) expand the * based on globing existing filenames.

Without the shell, you can’t echo anything. You may need to call the shell (bash for instance) to expand and echo it, or use the io package to list files based on this pattern

CodePudding user response:

If I understand correctly : in your bash command, echo "testDir/*" doesn't expand anything, it just outputs the string "testDir/*". echo ... > file is just one of the gazillion ways to set the file content to a given value from your shell.


If you want to write a fixed string to a file in go, just write it :

_, err := testFile.Write([]byte("testDir/*\n"))

no need to start some external process to echo a value on stdout.

  • Related