简体   繁体   中英

Exec command giving error "No such file or directory" when I try to execute the below code on cmd in golang with exec. Can someone help me with this?

"No such file or directory" when I try to execute the below code on cmd in golang with exec. This is basically because of the white spaces in this path ->

/Users/ltuser/Library/Application Support/Google/Chrome Beta/Default 

How do i escape the white spaces when executing with exec command in golang cmd in macos?

        cmdStr := fmt.Sprintf("find /Users/ltuser/Library/Application Support/Google/Chrome Beta/Default -mindepth 1 ! -name Preferences -delete")
        args := strings.Fields(cmdStr)
        cmd := exec.Command(args[0], args[1:]...)
        op, err := cmd.CombinedOutput()
        if err != nil {
            fmt.Println("error",err.Error())
        }

How do i escape the white spaces when executing with exec command in golang cmd in macos?

"find /Users/ltuser/Library/Application Support/Google/Chrome Beta/Default -mindepth 1 ! -name Preferences -delete"

It's important to distinguish between exec.Command and a shell statement. When you're running things at "the command line", you're running them in a shell. This lets you create pipelines with | , redirect with < , > , etc, use variables, and so on. It has a specific syntax for executing executables in the $PATH such as find . In shell syntax, a sequence of characters executable arg1 arg2 arg3 will be parsed around the spaces. executable , if a program found in the path, will be executed with exec . The arguments, split by spaces, will become the arguments to exec .

That's why when you run a command like your find at the shell, strings like /Users/ltuser/Library/Application Support/Google/Chrome Beta/Default must be enquoted if they're to be passed as one argument.

But you're not running this at the shell, even though you expressed your command as a sequence of string-separated values. That's why you

        args := strings.Fields(cmdStr)

That's where your path with spaces becomes multiple arguments.

exec.Command has an interface like the OS exec , because that's what it uses to execute your commands for you. And that's why it takes a list of strings; no parsing need be done, and no characters in the strings need to be escaped.

So just split up the arguments in the code, and pass them straight into exec.Command :

cmd := exec.Command("find", 
   "/Users/ltuser/Library/Application Support/Google/Chrome Beta/Default", 
   "-mindepth",
    ... ... ...,
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM