-1

How do I pass a list as a flag variable in Golang? For example in Bash you can pass a list as getopts to the script. Something like that:

./myScript.sh -n list_of_names.txt  //some file with about 50 names

and later loop over the list:

#!/bin/bash

while getopts "n:h:" options; do
  case "${options}" in
    "n") NAME=${OPTARG};;
    "h") PRINT_USAGE;;
  esac
done
for i in $NAME; do
  //TODO

I've heard about the "flag" package, but I have no idea how to achieve that

PS I'm a complete newbie to Go

kostix
  • 51,517
  • 14
  • 93
  • 176
Stead
  • 19
  • 3
  • 2
    Here's a starter example from the docs: https://golang.org/pkg/flag/#example_ – colm.anseo Apr 21 '21 at 17:21
  • 2
    `flag` is for receiving parameters, not sending them to another command. POSIX has no notion of a "list" parameter - all CLI args are simple strings. There's no Go code shown here; can you elaborate on what you're trying to do and show how you've tried to do it? – Adrian Apr 21 '21 at 17:37
  • I don't have one just yet, but I will need iterate over the passed list in a later stage. Apologies, maybe what I formulated is a bit misleading. What I'm trying to achieve is basically the same result as with a bash script, but in Golang – Stead Apr 21 '21 at 18:08
  • 1
    @Stead Are you asking how to iterate through the lines in a file specified by command line argument? – Charlie Tumahai Apr 21 '21 at 21:10
  • You seem to be very confused. You're not specifying a "list" as an argument, you're specifying a filename. What your program does with this filename is an entirely separate issue. For instance, how to read a file line by line has been answered on SO and elsewhere already. – Peter Apr 21 '21 at 21:22

1 Answers1

0

In your example, you really only have one required argument, so you don't really need to parse anything. You can just check the slice length:

package main
import "os"

func main() {
   if len(os.Args) != 2 {
      println("myScript <file>")
      os.Exit(1)
   }
   name := os.Args[1]
   println(name)
}

https://golang.org/pkg/os#Args

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Zombo
  • 1
  • 62
  • 391
  • 407
  • Yes in the example above, but that's just to outline what I need to achieve in Go. Basically I can't pass a whole bash script like that, I can use only variables as flags and one of those variables happens to be a list of servers, that I need to iterate over. Unfortunately I don't have any piece of Go code to share with you :( – Stead Apr 21 '21 at 18:18
  • 1
    @Stead if you want a good answer, you need to post a good question. Provide an example that actually needs the `flag` package, then let me know – Zombo Apr 21 '21 at 18:20