Parse Command Line Positional Arguments and Flags with Bash

Поділитися
Вставка
  • Опубліковано 25 січ 2025

КОМЕНТАРІ • 10

  • @er63438
    @er63438 8 місяців тому +1

    Great video, super helpful.

  • @peachpluslinux
    @peachpluslinux Рік тому +1

    Incredible guide. Thank you.

  • @armynyus9123
    @armynyus9123 Рік тому +1

    Good vid. Came also to the conclusion that parsing args like this is the way to go, compared to using getopt[s]. In a main function. Think only downside is that `foo=bar` can't be handled, would need a preprocessor.
    When the script is still in flux but already in use, I tend to generate help dynamically, from `cat $0` & grepping the switches between the case / esac in main, plus inline comments.

    • @NickJanetakis
      @NickJanetakis  Рік тому +1

      Thanks. Yep there's room for improvement to handle auto-generating the help menu. You could get cute with parsing comments as 1 line descriptions too.
      Sometimes I don't mind hard coding the help though. There's this idea of DRY for coding patterns but DAMP is not bad for certain things. Basically a little bit of duplication for the sake of optimizing for clarity (this often applies to writing test cases).

    • @armynyus9123
      @armynyus9123 Рік тому +2

      @@NickJanetakis Rite. Plus: FuncSpecs BEFORE coding make ton of sense - I guess writing a consitent help description can really help straighten designs...

  • @georgetait386
    @georgetait386 Рік тому

    is there a way to doing the same functionality using the getopts built in syntax? It worked nicely with flags for me but struggled with flags and positional arguments, so this video was a great help! But I can't help but thinking that getopts syntax would be able to handle this in a much more elegant manner

    • @NickJanetakis
      @NickJanetakis  Рік тому +1

      I haven't used getops a lot but based on stackoverflow.com/questions/11742996/is-mixing-getopts-with-positional-parameters-possible maybe not. It seems the limitation is when positional arguments appear before flags (check the comments in the marked answer). I'll admit I haven't looked into this too deeply tho. I Googled and found davetang.org/muse/2023/01/31/bash-script-that-accepts-short-long-and-positional-arguments/ but didn't really analyze to see if it would work with any order of flags and positional args.

  • @Zancb
    @Zancb Рік тому +1

    FYI, you can use `echo -e` to print out newlines. So it could have been:
    `echo -e "${1} must have a value

    " `
    You're barely saving any characters using echo. Just thought you would want to know there's another way to do it.

  • @soufiane_elbk
    @soufiane_elbk 8 місяців тому

    Ta7iya li Mohammed El Badry