doushou1298 2016-05-27 15:24
浏览 419
已采纳

使用filepath.Glob的Golang怪异行为

I'm confused about glob usage on Golang, I'm probably missing some environment variable. I don't know if I'm doing it right.

This code works perfectly fine when ran on my IDE (Intellij IDEA), but when this is ran on the OS via go run it doesn't work. I can't figure out what is the difference.

package main

import (
    "path/filepath"
    "fmt"
    "os"
)

func main() {

    file := os.Args[1]

    matches, err := filepath.Glob(file)

    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println(fmt.Sprintf("Number of matches:%d", len(matches)))
    fmt.Println(matches)
}

Running on OS

go run globtest.go /Users/bernardovale/glotest/*.bkp
Number of matches:1
[/Users/bernardovale/glotest/test1.bkp]

ls -l /Users/bernardovale/glotest/*.bkp
-rw-r--r--  1 bernardovale  staff  0 May 27 12:06 /Users/bernardovale/glotest/test1.bkp
-rw-r--r--  1 bernardovale  staff  0 May 27 12:06 /Users/bernardovale/glotest/test2.bkp
-rw-r--r--  1 bernardovale  staff  0 May 27 12:06 /Users/bernardovale/glotest/test3.bkp

Running on IntelliJ IDEA

go run on the IDEA

  • 写回答

1条回答 默认 最新

  • dpmkif3097 2016-05-27 16:43
    关注

    The difference here is that the shell is executing the glob and providing the individual values to your application. When executing from a shell you should wrap a glob in double quotes to make sure it's not evaluated by your shell first. See the example below.

    Seans-MBP-2:~ sthorne$ echo Testing*
    Testing Testing2 Testing3
    Seans-MBP-2:~ sthorne$ echo "Testing*"
    Testing*
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化