cobra
cobra copied to clipboard
failed parse ~ to $HOME when use = in flag assignment
I want to open file with filepath assigned in flag
This is my code
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
var (
file string
rootCmd = &cobra.Command{
Use: "",
Short: "",
Long: "",
Run: func(cmd *cobra.Command, args []string) {
if _, err := os.Stat(file); os.IsNotExist(err) {
fmt.Println(err.Error())
} else {
fmt.Println(file)
}
},
}
)
func init() {
rootCmd.PersistentFlags().StringVarP(&file, "file", "f", "", "file path")
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
And the execute results are:
without =, successed parse ~ to $HOME
root@LAPTOP-VFP625S5# ./main --file ~/.kube/config
/root/.kube/config
with =, failed parse ~ to $HOME
root@LAPTOP-VFP625S5# ./main --file=~/.kube/config
stat ~/.kube/config: no such file or directory
Is that any ways can make it parse ~ successful with = ?