Chapter 15

  1. Why are flags often used as modifiers whereas positional parameters are used as targets?
    Flags often modify the behavior: it can make a script more or less verbose, or perhaps write the output somewhere. Often, a command manipulates a file, which is then considered the primary target for what the command actually tries to achieve.
  2. Why do we run getopts in a while loop?
    All flags are parsed sequentially, and when getopts can no longer find new flags it will return an exit code different from 0, which will exit the while loop at exactly the right moment.
  3. Why do we need a ?) in the case statement?
    We cannot trust the user to correctly use all flags all the time. ?) matches any flag we have not specified, which we can then use to inform the user of incorrect usage.
  4. Why do we (sometimes) need a :) in the case statement?
    The :) is used when the optstring specifies an argument for an option, but the user has not given it. It allows you to inform the user of the missing information (and you will most probably abort the script at this point).
  5. Why do we need a separate optstring is we're resolving all options anyway?
    Because the optstring will tell getopts which options have arguments and which do not.
  6. Why do we need to substract 1 from the OPTIND variable when we use it in shift?
    The OPTIND variable always refers to the next possible index, which means it is always 1 ahead of the final flag that was found. Because we only need to shift away the flags (which are seen as positional arguments!), we need to make sure we reduce the OPTIND by 1 before we shift.
  7. Is it a good idea to mix options with positional arguments?
    Because of the added complexity of dealing with both options and positional arguments, it is often better to specify the target of your operation as a flag argument for the -f flag; -f is almost universally excepted as a file reference, which will always be considered as a logical target for most operations.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.116.112