展开波浪号到主目录 [英] Expand tilde to home directory

查看:26
本文介绍了展开波浪号到主目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序接受将在其中创建文件的目标文件夹.我的程序应该能够处理绝对路径和相对路径.我的问题是我不知道如何将 ~ 扩展到主目录.

I have a program that accepts a destination folder where files will be created. My program should be able to handle absolute paths as well as relative paths. My problem is that I don't know how to expand ~ to the home directory.

我扩展目的地的函数如下所示.如果给定的路径是绝对路径,则不执行任何操作,否则会将相对路径与当前工作目录连接起来.

My function to expand the destination looks like this. If the path given is absolute it does nothing otherwise it joins the relative path with the current working directory.

import "path"
import "os"

// var destination *String is the user input

func expandPath() {
        if path.IsAbs(*destination) {
                return
        }
        cwd, err := os.Getwd()
        checkError(err)
        *destination = path.Join(cwd, *destination)
}

由于 path.Join 不会扩展 ~ 它不会如果用户将 ~/Downloads 之类的内容作为目标传递,则不起作用.

Since path.Join doesn't expand ~ it doesn't work if the user passes something like ~/Downloads as the destination.

我应该如何以跨平台的方式解决这个问题?

How should I solve this in a cross platform way?

推荐答案

通常情况下,~ 会在您的程序看到它之前 被 shell 展开.
以与 shell 扩展机制兼容的方式调整您的程序如何从命令行获取其参数.

Normally, the ~ is expanded by the shell before your program sees it.
Adjust how your program acquires its arguments from the command line in a way compatible with the shell expansion mechanism.

可能的问题之一是像这样使用 exec.Command:

One of the possible problems is using exec.Command like this:

cmd := exec.Command("some-binary", someArg) // say 'someArg' is "~/foo"

不会被扩展.例如,您可以改为使用:

which will not get expanded. You can, for example use instead:

cmd := exec.Command("sh", "-c", fmt.Sprintf("'some-binary %q'", someArg))

这将从 shell 获得标准的 ~ 扩展.

which will get the standard ~ expansion from the shell.

修复了sh -c"示例.

fixed the 'sh -c' example.

这篇关于展开波浪号到主目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆