GETFLAGS(1plan9)

πŸ’– GETFLAGS πŸ’–

okay bestie, listen up β€” this is a plan9 section 1 situation, and we're talking about command-line parsing for shell scripts. two lil utilities: getflags and usage. they are the dynamic duo of not letting your script choke on -x and friends. periodt. πŸŽ€


✨ SYNOPSIS ✨

getflags $*
usage [ progname ]

πŸ¦‹ DESCRIPTION πŸ¦‹

πŸ’… getflags

so getflags looks at the options in its command-line arguments and parses them according to the environment variable $flagfmt. it's giving "i read the rules and i follow them". πŸ‘‘

$flagfmt needs to be a list of comma-separated options. and each option is one of two vibes:

  • a single letter β€” meaning it does not take arguments
  • a letter followed by the space-separated names of its arguments

then getflags prints an rc(1) script on standard output, and that script initializes the environment variable $flagx for every option mentioned in $flagfmt. every single one. no option left behind fr fr.

here's the tea on what that script does per option:

  • if the option is not present on the command line β†’ the script sets that option's flag variable to an empty list
  • if the option is present β†’ the script sets that option's flag variable to a list containing the option's arguments... or, if the option takes no arguments, to the string 1. slay.

and the script also sets the variable $* to the list of arguments that come after the options. ✨

the final line of the script sets the $status variable:

  • empty string on success πŸ’–
  • the string usage when there's an error parsing the command line πŸ’€

🌸 usage

usage prints a usage message to standard error. dramatic? maybe. necessary? absolutely.

it builds that message out of:

  • $flagfmt, as described above πŸ‘†
  • $args, which should contain the string to be printed explaining non-option arguments
  • $0, the program name (see rc(1))
⚠️ important bestie: if you're running under sh(1), which does not set $0, then you have to give the program name explicitly on the command line. no shortcuts, no vibes, just type it. 😭

🌈 EXAMPLE 🌈

let's parse the arguments for leak(1) β€” iconic behavior honestly:

flagfmt='b,s,f binary,r res,x width'
args='name | pid list'
if(! ifs=() eval `{getflags $*} || ~ $#* 0){
     usage
     exit usage
}

see how $flagfmt and $args are just... sitting there, being set, doing their thing? that's the whole mood. πŸ’œ


πŸ“ SOURCE πŸ“

/src/cmd/getflags.c
/src/cmd/usage.c

πŸ‘‘ SEE ALSO πŸ‘‘


okay that's the whole page, you ate it, you understood it, you're a shell-scripting main character now πŸ’…βœ¨ this was GETFLAGS(1plan9) from the plan9 manual, section 1 β€” go forth and parse responsibly, bestie 🫢🌸

πŸ“¦ where this page comes from