This solution has very bad design… You do not know order of eveluating those flags.
The issue
I am assuming you are using cobra
. So when you read documentation you will not find any part of how your flags are evaluated. So sometimes it is called undefined behavior and it may work but if the future it may be changed
Let’s analyze your example:
deleteCmd.Flags().StringVarP(&option, "wallet", "w", "", "Specify the wallet to be deleted")
deleteCmd.Flags().StringVarP(&option, "holding", "o", "", "Specify the holding to be deleted")
deleteCmd.Flags().StringVarP(&option, "ticker", "t", "", "Specify the ticker to be deleted")
deleteCmd.Flags().StringVarP(&option, "tag", "g", "", "Specify the tag to be deleted")
You have the following flags: wallet, holding, ticker, tag
. We can assume order is how you put it in your code. Let’s say potential behavior:
User put the ticker
flag. Default value for all flags is empty. So the option
variable has an empty value, which comes from the tag
flag.
The solution
You should use separated variable for each flag. And you should implement your logic to cover the part to determine which flag has been put.
deleteCmd.Flags().StringVarP(&wallet, "wallet", "w", "", "Specify the wallet to be deleted")
deleteCmd.Flags().StringVarP(&holding, "holding", "o", "", "Specify the holding to be deleted")
deleteCmd.Flags().StringVarP(&ticker, "ticker", "t", "", "Specify the ticker to be deleted")
deleteCmd.Flags().StringVarP(&tag, "tag", "g", "", "Specify the tag to be deleted")
if wallet != "" {
option = wallet
selected = "wallet"
} else if holding != "" {
option = holding
selected = "holding"
} else ...
...
...
1
solved How can I get the Flag chosen by the user in my CLI