4 ms·
This is exactly how I write my Bash functions. I didn't even realize it was a standard, it just made the most sense to me. Being given help via a --help argumen
by pmarreck 3y ago
This is exactly how I write my Bash functions. I didn't even realize it was a standard, it just made the most sense to me. Being given help via a --help argument is intentional and thus appropriate for STDOUT (and a return code of 0); being given help after an argument error makes sense to go to STDERR (and a return code of 2, "USAGE").
Since you can nest functions in Bash (did you know?), I usually have a help function within the main function that is called from both logic branches and just outputs to the right file descriptor.
- kazinator 3y ago> (did you know?) Yes, but they are not scoped to the parent: $ foo() > { > bar() > { > echo 42 > } > } $ foo $ bar # bar can be called though we are not in foo! 42 Probably the most profitable use for this is for individual functions to override some callback. But without even dynamic scope, you have no nice way of restoring the previous one, which could be one that some intermediate caller installed for itself. It could be used to delay the definition of functions. Say that for whatever reason, we put a large number of functions into a file and don't need them all to be defined at once. There can be functions which, when invoked, define sets of functions. A module could be written in which certain functions are intended to be clobbered by the user with its own implementation. A function which defines those functions to their original state would be useful to recover from a bad redefinition, without reloading that module.
- OJFord 3y agoHm, and not with `local bar` either, bit of a shame. I think at the point that mattered I wouldn't want to be using bash though! It's nice just as a grouping, 'this is related to that' sort of thing.
- pmarreck 3y agoThat is unfortunate and true. I wish I could use Elixir as a shell scripting language without incurring the VM startup cost and losing the ability to export shell variables or create shell functions... Maybe it would make sense for someone to hack its REPL to dupe most of what one would need on a commandline
- kazinator 3y agoAre you sure? I would be astonished if Erlang didn't have a way to export environment variables for child processes. In a language that provides nothing beyond a function that lets you run system commands, you can control the child's environment via the env utility: system("env FOO=bar command arg ...");
- pmarreck 3y agoThe context here is that I may want to run an Elixir script from a Bash command line which results in some environment variables being changed. I don't think that's possible unless that script itself sends that env command to STDOUT, and I then capture it and eval it on the Bash side. Which seems... inelegant.