我正在尝试编写一个简单的golang程序,列出目录中的文件.每当我的shell命令产生多行时,它就会在Go中作为数组注册
例如,当我尝试以下内容时:
import (
"log"
"os/exec"
"fmt"
)
func main (){
out,err := exec.Command("ls").Output()
if err != nil {
log.Fatal(err)
}
fmt.Println(out)
}
Run Code Online (Sandbox Code Playgroud)
我最终得到了输出 [101 108 105 109 115 116 97 116 115 46 105 109 108 10 101 110 118 10 115 99 114 97 116 99 104 10 115 114 99 10]
我觉得这是常见的事情,但无法在任何地方找到它.
我试图调用内建函数find以打印出子文件夹my-files中所有文本文件的内容。我知道可以使用更简单的方法来执行此操作,但是我需要使其与exec一起使用。我怀疑exec无法正确处理报价。我的初始代码如下:
fullCmd := "find my-files -maxdepth 1 -type f"
cmdParts := strings.Split(fullCmd, " ")
output, _ := exec.Command(cmdParts[0], cmdParts[1:]...).CombinedOutput()
fmt.Println("Output is...")
fmt.Println(string(output))
Run Code Online (Sandbox Code Playgroud)
这可以正常工作并打印出来
Output is...
my-files/goodbye.txt
my-files/badfile.java
my-files/hello.txt
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试开始添加“奇怪”字符时,它会崩溃。如果我将第一行更改为
fullCmd := "find my-files -maxdepth 1 -type f -iname \"*.txt\""
Run Code Online (Sandbox Code Playgroud)
什么都没打印出来。更糟糕的是,如果我将行更改为:
fullCmd := "find my-files -maxdepth 1 -type f -exec cat {} \\;"
Run Code Online (Sandbox Code Playgroud)
使用此标准输出查找错误:
Output is...
find: -exec: no terminating ";" or "+"
Run Code Online (Sandbox Code Playgroud)
我以为我正确地逃避了必要的角色,但我想不是。关于如何使命令起作用的任何想法?作为参考,当直接在命令行上输入此命令时,它确实满足我的要求:
find my-files -maxdepth 1 -type f -iname "*.txt" -exec cat {} \;
Run Code Online (Sandbox Code Playgroud) 我遇到了这个页面,我制作了这个文件
#include <unistd.h>
int main(void) {
exec("ls");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然而,编译它给了我这个消息
$ cc foo.c
undefined reference to `exec'
Run Code Online (Sandbox Code Playgroud)
这个页面是假的吗?过时了?这里发生了什么?
我想从 TCL 脚本运行这个 linux 命令:
uname -a | awk '{print $2}'
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?