将代字符展开到主目录 [英] Expand tilde to home directory
问题描述
我有一个程序接受目标文件夹的文件将被创建。我的程序应该能够处理绝对路径以及相对路径。我的问题是我不知道如何将〜
展开到主目录。
我的函数目的地看起来像这样。如果给定的路径是绝对路径,则它不会执行任何操作,否则它会将当前工作目录的相对路径加入。
importpath
导入os
// var destination *字符串是用户输入
func expandPath(){
如果path.IsAbs(* destination) {
return
}
cwd,err:= os.Getwd()
checkError(err)
* destination = path.Join(cwd,* destination)
自 path.Join
不会展开〜
如果用户通过如〜/ Downloads>
作为目的地。
我应该如何以跨平台的方式解决这个问题?
通常情况下,〜您的程序会看到它。
调整您的程序如何从命令行获取它的参数以一种与shell扩展机制兼容的方式。
其中一个可能的问题是使用 exec.Command 像这样:
cmd:= exec。 Command(some-binary,someArg)//说'someArg'是〜/ foo
它不会扩大。例如,您可以使用:
cmd:= exec.Command(sh,-c,fmt。 Sprintf(some-binary%q',someArg))
这将得到标准的<
编辑:修正'sh -c'的例子。
$ b $> code>〜从shell中扩展。 $ bI 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)
}
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?
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.
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))
which will get the standard ~
expansion from the shell.
EDIT: fixed the 'sh -c' example.
这篇关于将代字符展开到主目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!