20 ms·
Bash functions are better than I thought
- gjvc 5y agoin bash, strongly prefer functions to aliases
- agumonkey 5y agolet's make a script that migrate .aliases to named functions
- arp242 5y agozsh has "always", which behaves as "try .. finally" and such in some other languages: { foo } always { cleanup stuff }
- sundarurfriend 5y ago`always` is a much better name for that feature.
- jrochkind1 5y agoWait, a subshell is a child process, right? I would imagine there would be performance implications of defining every bash function as a subshell, is why it's not universally recommended to define functions this way? No?
- deleted 5y ago[deleted]
- zegl 5y agoI did a quick test, and function calls using the subshell type of function seems to be about twice as slow as normal function calls. #!/bin/bash fib1() { if (( $1 < 2 )) ; then echo $1 return 0 fi echo $(( $(fib1 $(($1-1))) + $(fib1 $(($1-2))) )) return 0 } fib2() ( if (( $1 < 2 )) ; then echo $1 return 0 fi echo $(( $(fib2 $(($1-1))) + $(fib2 $(($1-2))) )) return 0 ) time fib1 15 time fib2 15 Result: 610 real 0m1.585s user 0m0.590s sys 0m0.972s 610 real 0m3.168s user 0m1.068s sys 0m2.025s
- jrochkind1 5y agoIt probably doesn't matter too much if you have only a handful of function invocations in your exec. But if you have a a couple orders of magnitude more... RAM is going to be an issue too maybe. Creating a new process for every single function invocation seems crazy to me, and but might actually be just fine for many "ordinary" use cases? (Although might not have been on computers of 20+ years ago, which might also be why it's not something advised, so much of bash tradition is decades old?)
- kevincox 5y agoOf course the subshell is copy-on-write so the ram requirements shouldn't be huge. But assuming some stack you are using at least some stack in each process you are looking at 4k per call which adds up fairly quickly.
- chubot 5y agoYes, and that's my reaction too. While I can see the rationale for always starting another process, in practice I haven't found the leakage to be a big problem. Actually Oil functions don't use dynamic scope, but this is done in-process, not with another process: https://www.oilshell.org/release/latest/doc/variables.html#procs-dont-use-dynamic-scope https://www.oilshell.org/release/latest/doc/variables.html#p... ---- Also nested functions don't really add much useful to shell. It's purely a matter of textual code organization and doesn't affect the semantics. I define all functions at the top level.
- fragmede 5y agosubshells don't propagate information out which makes them hard to work with in many cases. Ie ((foo=42)); echo $foo is not going to have 42.
- dataflow 5y agoYeah, try subshells on MSYS2 and see how performance goes.
- laumars 5y agoIf your hot path needs that level of micro-optimisation then you’re far better off rewriting it an language that compiles instead of interprets and forks. Even Ruby and Perl would run circles around Bash.
- arendtio 5y agoIf you care about performance, you better don't write shell scripts. The typical task of a shell script is to start programs and connect them in a meaningful way. This is in itself a pretty expensive task performance wise. So arguing about the cost of sub-shells is somewhat besides the point.
- dorianmariefr 5y agoJust write scripts in Ruby
- hackbinary 5y agoOr Python, or tcl, or (eeek) Perl, or JavaScript. Or anything that can handle integers and floating point calculations natively.
- aaaaaaaaaaab 5y agoBash handles integers natively.
- forinti 5y agoIt doesn't really make sense to be squirmish about Perl in a discussion about bash.
- nanomonkey 5y agoBabashka for Clojure is my new favorite scripting language.
- agumonkey 5y agoSeriously impressive
- jrochkind1 5y agoInstalling ruby/predicting the version of ruby installed/writing ruby that can run on any version installed... is unfortunately non-trivial. I think pretty much the only reason people write bash is because you have an incredibly high chance of bash being installed and a version of bash being installed that will run whatever bash you write just fine. Perl is honestly almost as reliable to be there predictably and compatibly... but I guess people would rather write bash than Perl?
- CSSer 5y agoIs there any risk of Bash ever going away? It seems like it's the de facto shell. I remember considering whether or not I should learn Perl at one point. It didn't even feel like a choice with Bash. Trendy shells seem like they have no choice but to support it too. I feel like what usually makes me reach for something beyond Bash is really a matter of wanting or needing some dependency that wasn't written in it for whatever reason. Usually this happens right at the point where the script/utility starts to turn into a library/program, so it's trivial to just transpose the control flow into whatever language is required at that point and go from there. This of course raises the type of concern you mentioned about Ruby, but at that point it's hopefully worth the trouble to address.
- boardwaalk 5y agoPeople do underestimate the shell. Particularly I see people shoehorning collections of commands into a Makefile, when a shell script would work just fine. On the other hand, with a lot of glue work I do, I eventually want to something more complex (use lists and maps, complex string building and regexes, date handling) and while you /can/ do that in bash, I might as well start in Python and have everything in one language and take advantage of things like code sharing via modules. (And yes you can share code in shell, but again it’s not as nice.)
- fragmede 5y agoMight as well, yes, but I've found writing shell scripts in Python to be cumbersome because whatever flavor of os.system() I end up using just doesn't work well syntactically. I can run a command and pipe to a bunch more commands way easier in a shell because I'm already using a shell when interacting with the computer. Perl had this figured out, but proved unable to continue evolving (aka adding types, like Python/Ruby/JavaScript have managed to.) If there's a modern library/workflow that makes this not the case, I'm all ears!
- ilyash 5y ago> writing shell scripts in Python to be cumbersome because whatever flavor of os.system() I end up using just doesn't work well syntactically. This is exactly how I felt. Bash can't handle structured data well. Python (being general purpose programming language) can't handle calling external programs well because it's not the "focus" of the language. My shameless plug solution is a "real" programming language that can do both well (along with proper handling of exit codes and more goodies for "devops"y scripting). https://github.com/ngs-lang/ngs https://github.com/ngs-lang/ngs More about this feeling when you don't have a well fitting language for "devops"y scripting - https://ilya-sher.org/2017/10/10/why-i-have-no-favorite-programming-language/ https://ilya-sher.org/2017/10/10/why-i-have-no-favorite-prog...
- laumars 5y agoThere’s a few of these types of shells floating about these days. I personally use murex but Elvish seems popular too.
- chaps 5y agoOh yeah, bash functions are great and absolutely abusable. Sometimes you need some grand hacks to get it to work well, but when it works well, it can do some magic. You can even export functions over ssh! I wrote this a few years back which ran on bunches of hosts and fed into an infrastructure network mapper based on each hosts' open network sockets to other known hosts. It wasn't really feasible to install a set of tools on random hosts.. but I still had root ssh access across the board. So I needed something tool agnostic, short, auditable, and effectively guaranteed to work: https://github.com/red-bin/lsofer/blob/master/lsofer.sh https://github.com/red-bin/lsofer/blob/master/lsofer.sh
- throwawaygh 5y ago> You can even export functions over ssh! What does "export" mean in this context? Do you just mean `ssh host cmd` where cmd is some shell that happens to contain (and call) a function?
- xyzzy_plugh 5y agoProbably implying use of `declare -pf` to turn functions into strings which can be evaluated by a remote shell.
- chaps 5y agoExactly -- check out script in the link, it shows how it would be used. I'm not sure why the first `remote_cmd` is called (probably local testing and forgot to delete it), so ignore that. Try this and you'll see how it returns a dramatic amount of bash as its output: remote_cmd="`typeset -f` ; function test123 { echo hi! ; }" && echo -e $remote_cmd
- throwawaygh 5y agoAh, makes sense! Yeah, that's nice. You can do something similar with scripting languages by piping source code into the interpreter. Super useful back in the day for doing crap on machines in an LSF cluster when the NFS was down/slow.
- nickjj 5y agoYou can also turn a Bash function into a script command with almost no effort, such as making a file called "run" and putting this in it: #!/usr/bin/env bash set -eo pipefail function hey { echo "Hey!" } TIMEFORMAT=$'\nTask completed in %3lR' time "${@}" Now after running a `chmod +x hey` can run it with: ./run hey Feel free to replace "time" with "eval" too if you don't want your command timed. This is a really useful pattern because it means you can create a "run" script with a bunch of sub-commands (private or public), auto-render help menus and create project specific scripts without any boilerplate. Bash also supports having function names with ":" in the name so you can namespace your commands like "./run lint:docker" or "./run lint:frontend". I have a practical example of this sort of thing here: https://github.com/nickjj/docker-flask-example/blob/main/run https://github.com/nickjj/docker-flask-example/blob/main/run I've written about this pattern in more detail here https://nickjanetakis.com/blog/replacing-make-with-a-shell-script-for-running-your-projects-tasks https://nickjanetakis.com/blog/replacing-make-with-a-shell-s.... It's basically a less limited Makefile for when you want to make project specific aliases. This is something I use all the time now.
- abbeyj 5y agoIf you don't want the timing, use `"${@}"`, not `eval "${@}"`. The latter will parse all of your arguments through the shell an additional, unwanted time. For example, take the command `./run echo "Don't"`. When using `time`, this will print `Don't`. If you use just `"${@}"`, it will also print `Don't`. But if you use `eval "$@"`, this will crash with an error like eval: line 10: unexpected EOF while looking for matching `''
- francislavoie 5y agoI do the same thing, but slightly differently. https://github.com/francislavoie/laravel-websockets-example/blob/main/docker/utils https://github.com/francislavoie/laravel-websockets-example/...
- quotemstr 5y agoOne of my biggest pet peeves is people defining commands and utilities as shell functions and demanding I source some environment setup script instead of just making regular command scripts and running them as normal programs. My shell is my computing environment. It's rude for a script author to make me change my computing environment when he could just as easily have made a script and created his own sandboxed environment that wouldn't interfere with mine. People should never ship end user interfaces as bundles of shell functions that have to be sourced. (I'm looking at you, Android build system.)
- ridiculous_fish 5y agoFun shell function fact: used to be if you `break` or `continue` in a function without a loop, bash would find the loop: breaker_breaker() { break; } foo() { breaker_breaker; } while true; do echo Loop foo done bash dynamically crawled up the call stack until it hit a break-able loop. If you squint it almost looks like exception handling! Anyways this no longer works in bash, though it still does in zsh.
- Sniffnoy 5y agoHeh, kind of like dynamic scoping, except as applied to control flow...
- barosl 5y agoThat's very impressive, it almost feels like a legit useful hack. Why was it not fixed in zsh? Did they decide it was working as intended?
- naniwaduni 5y agoWell, bash's new behaviour (noisily complain and do nothing, reporting success) doesn't do anything useful, so implementing it gratuitously breaks old code to no gain. Dynamic stack-crawling is more or less the most popular historical behaviour (though afaict the Bourne/Korn lineage just silently fails breaks outside the enclosing function); it's just generally consistent with everything else in the shell that's globally/dynamically scoped. Even in the shells where you can't break out of your enclosing function, `eval break` still breaks through loops in your current context, and that kind of looks like a function you called that called break if you squint. (POSIX expressly leaves this case undefined with a carveout for break/continue inside the body of a function lexically contained within a loop.)
- dllthomas 5y ago> If you squint it almost looks like exception handling! It also reminds me of TCL's "uplevel": https://www.tcl.tk/man/tcl8.4/TclCmd/uplevel.html https://www.tcl.tk/man/tcl8.4/TclCmd/uplevel.html
- VWWHFSfQ 5y ago> Essentially, the only "advantage" of not running your functions in a subshell is that you can write to global variables. subshells are ridiculously slow because it's a forked child process. imagine forking for every function call in your program.... > I simply do not understand why people keep recommending the {} syntax at all. because it's almost always what you actually want.
- fulafel 5y agoEverything is relative, a $(true) is on the order of 0.1 milliseconds. If this makes something ridiculously slow, you may be implementing a too big part of your work in bash!
- SubiculumCode 5y agoI'd argue that most of the work in a bash program is done by functions like find, grep, etc, and that the time to fork is not all that relevant. We don't program the same kinds of things in bash that we might in C++
- fiddlerwoaroof 5y agoYeah “fork is slow” is the sort of microbenchmark that is mostly irrelevant for shell scripts: every command you run in a script is basically a fork.
- VWWHFSfQ 5y agoif you want to fork your function call then you do it explicitly with $(my_function). I'm aware that people are always discovering things for the first time but there is literally decades of thought that has gone into why bash behaves the way it does. and there's a pretty good reason why the bash authors decided not to make function calls fork by default...
- deleted 5y ago[deleted]
- 5y ago
- thangalin 5y agoBash can also employ a kind of function pointer, which can greatly simplify command-line argument parsing. Consider the following simplified example: ARG_ARCH="amd64" ARGUMENTS+=( "ARG_ARCH,a,arch,Target operating system architecture (${ARG_ARCH})" "log=utile_log,V,verbose,Log messages while processing" ) utile_log() { echo "$1" } noop() { return 1 } log=noop By creating a comma-delimited list of command-line arguments, the parsing logic and control flow can be influenced from a single location in the code base. The trick is to eval-uate "log=utile_log" when the "-V" command-line argument is provided (or assign ARG_ARCH to the user-supplied value after "-a"). Using the $log variable invokes the function, such as in: preprocess() { $log "Preprocess" } If "-V" isn't supplied, then every invocation of $log simply returns without printing a message. The upshot is a reduction in conditional statements. Function pointers FTW. I wrote about this technique in my Typesetting Markdown series: https://dave.autonoma.ca/blog/2019/05/22/typesetting-markdown-part-1/ https://dave.autonoma.ca/blog/2019/05/22/typesetting-markdow... Here's a rudimentary implementation and example usage to wet your whistle: https://github.com/DaveJarvis/keenwrite/blob/master/scripts/build-template https://github.com/DaveJarvis/keenwrite/blob/master/scripts/... https://github.com/DaveJarvis/keenwrite/blob/master/installer.sh https://github.com/DaveJarvis/keenwrite/blob/master/installe...
- Izkata 5y agoIt also works with dynamic names, if you need a slightly different entry point and don't want to risk conflicting with other function names: run_foo() { echo foo; } run_bar() { echo bar; } name=foo run_$name
- hnlmorg 5y agoThis kind of thing terrifies me when I see it in in code -- particularly when it's something like `$VAR -flags` -- because my first thought is always > "what if that variable isn't set to whatever the developer is expecting it to be set? What random command will then be executed?" As an author of an alternative shell myself, I purposely removed this ability for that reason.
- dontcare007 5y agoBash scripting helped me out of a big problem a couple of decades ago. It's nice to have a tool around that doesn't change out from under you.
- kzrdude 5y agoThis-all is actually not exactly about bash functions, but POSIX shell functions: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_05 https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V... `local` is not in POSIX, but is so common in "posix" shells that many use it, just a sidenote.
- notatoad 5y ago>`local` is not in POSIX So maybe it is about bash functions and not posix functions, because it's refencing features that exist in bash but not posix?
- throwaway984393 5y agoGetting anything out of a subshell that isn't from STDOUT is impossible. So you can't define an array in a subshell and then use it outside the subshell, and you can't return an array (or anything that isn't a string) from a subshell. If you only use subshells and want to use any kind of data structure that isn't a string passed from STDOUT, you have to do it globally. And subshells are slow. So nobody uses subshells. If you use Bash for programming, you have to stop thinking in terms of the holier-than-thou software engineer, whose ego believes that a superior, "clean" design makes a superior program. You should embrace globals. You should switch between using or not using the enforcement of set variables or program exit status. You should stop using Bashisms and subtle, obscure language features unless you absolutely have to. Bash is not a "real" programming language, so do not treat it as one. Do not look for hidden features, or try to do things in cute ways that nobody else uses. There is no superior method or hidden knowledge. Just write extremely simple code and understand the quirks of the shell.
- 1vuio0pswjnm7 5y ago"So nobody uses subshells." djb has always used them, even in the shortest of scripts. Otherwise I agree with everything in this comment. There is a reasonable argument to avoid using bash for non-interactive scripts. The benefits of any additional bash features, so-called "bashisms", arguably do not outweigh the costs of making these scripts non-portable. One of the many advantages of shell scripts is that they are portable and have tremendous longevity; shell scripts can last a long, long time. There are no version changes and aggressive feature creep to worry about as is routinely the case with programming languages. The scripts just keep working, every day, and we can forget we are even using them, e.g., they are being used in the various ways by UNIX-like OS distributions. One of the today's programmer memes was "Get Stuff Done". Maybe the shell was not meant for today's programmers. But for "sysadmins", or "DevOps", or whatever term anyone comes up with in the future, people who can "administer/operate" computers running a UNIX-like OS for themselves or for someone else like a client or an employer, the Bourne shell works for its intended purpose, better than anything anyone has come up with in the last 50+ years. There's a lot of stuff that "gets done" with the shell, whether it is on someone's own computer, their client's or their employer's. Attempts at "shell replacements", cf. alternative shells, usually look like interpreters for programming languages, not shells. Perhaps this is not a coincidence. Bourne shell is relatively small and fast. Computers with small form factors often use UNIX-like OS and when they do they usually include shells. Many programmers seem to dislike the notion that such a layer exists. They often try to blame the shell instead of their own lack of interest in learning to use it. The shell is boring, and "boring" is sometimes the wisest choice. Most software has expanded to consume available resources (often the developer's choice not the user's). This makes computer performance gains difficult for the end user to discern, e.g., decade after decade, routine tasks seem to take the same amount of time. However the shell and many "standard" UNIX utilities have not changed as much in the same period. Subshells may have been "slow" many years ago. IMHO, they do not feel slow today. Routine tasks performed with the shell seem to run faster, as one would expect after hardware upgrade. I posit: Life is too short to learn every programming language du jour but it is long enough to learn the Bourne shell, reasonably well.
- 2Gkashmiri 5y agoI want to disable my USB controller so after every boot, I am forced to open terminal, type Sudo -s , give password and unbind the USB. Is there a way to automate this as a shell script without having to type the password? I assume Sudo -s | password | unbind string but that doesn't work.
- Hackbraten 5y agoYou want to use your service manager for that kind of tasks. For example, systemd or sysvinit on Linux, or launchd on macOS.
- kafkaIncarnate 5y agoLook into NOPASSWD in the sudoers manpage. You can just put the code in a script then give %wheel (or whomever) NOPASSWD access to run it. This can also be thrown in sudoers.d for ease of copying and managing config across machines.
- jacob019 5y agouse an rc.local script
- sp332 5y agoYou can configure udev to blacklist the device. https://projectgus.com/2014/09/blacklisting-a-single-usb-device-from-linux/ https://projectgus.com/2014/09/blacklisting-a-single-usb-dev...
- qbasic_forever 5y agoYep, do this OP... don't try to hack in some automated script that now has a race condition with device setup. udev has a ton of hooks for enabling, disabling and doing anything when device state changes.
- smarx007 5y agoAdditionally, 'local -n' allows to define a local variable as a reference, useful with arrays, for example.
- barosl 5y ago> Subshells are, as the name suggests, running in a subshell. They don't strictly have to be OS subprocesses Are there really cases where subshells are invoked within the same process? In my experience, it has never been the case. That's why I've been trying to minimize the use of subshells because spawning a new process is a bit slow.
- cryptonector 5y agoWhile it's probably true that subshells don't strictly have to fork(), I'm willing to bet Bash does it every time and never optimizes away the fork().
- pdkl95 5y ago> Well, because it simply doesn't work for them: returning from a function does not trigger the EXIT signal. It doesn't trigger EXIT, but it does trigger RETURN. Just trap both: #!/bin/bash foo() { trap "echo 'Cleanup!'" RETURN EXIT #return #exit echo "Kill me with ^C or \"kill $$\"" while true ; do : ; done } foo # should print 'Cleanup!' on SIGTERM, # returning, or calling exit
- gavinray 5y agoI write a LOT of bash/shell scripts. And I don't like it, it's just part of what I have to do. Learning a handful of bash idioms and best-practices has made a massive impact for me, and life much easier. The shell is something you cannot avoid if you're a programmer or other sort of code-wrangler. You can interact with it + be (mostly) clueless and still get things done, but it's a huge return-on-investment to set up "shellcheck" and lookup "bash'isms", etc. ---- (Off-topic: I am convinced Ruby cannot be beaten for shell-scripting purposes. If I had a wish, it would be that every machine had a tiny Ruby interpreter on it so I could just use Ruby. I'm not even "a Ruby guy", it's just unreasonably good/easy for this sort of thing. And I keep my mind open for better alternatives constantly.) Example of near-identical script in bash vs Ruby: https://github.com/GavinRay97/hasura-ci-cd-action/blob/master/entrypoint.sh https://github.com/GavinRay97/hasura-ci-cd-action/blob/maste... https://github.com/GavinRay97/hasura-ci-cd-action/blob/master/main_alt.rb https://github.com/GavinRay97/hasura-ci-cd-action/blob/maste... I'm not sure how much closer to describing your exact intent in English a language can get than: successfully_made_executable = system 'chmod +x /usr/local/bin/hasura' abort 'Failed making CLI executable' unless successfully_made_executable Though I have NOT written Perl (either old Perl, or Raku/Perl 6) but I do believe it may be roughly this semantic too. EDIT: Looks like Perl/Raku is essentially the same as Ruby in this regard. So besides it being a whacky language, take that for what you will: $successfully_made_executable = shell "chmod +x /usr/local/bin/hasura" die 'Failed making CLI executable' unless $successfully_made_executable.exitcode is 1
- jrochkind1 5y ago> I'm not sure how much closer to describing your exact intent in English a language can get than: > successfully_made_executable = system 'chmod +x /usr/local/bin/hasura' > abort 'Failed making CLI executable' unless successfully_made_executable I guess, but if I was writing scripts like this, I'd really want to write a helper method something like: def system_or(cmd, fail_msg) system cmd || abort fail_msg end # and then system_or 'chmod +x /usr/local/bin/hasura', 'Failed making CLI executable' Instead of having to write every single `system` call as boilerplate two liners with an immediate-throwaway local var.
- louwrentius 5y agoAt one time, I did learn myself to write shell scripts. I even wrote this 3Kl line monstrosity [0] However, I would strongly advice to master a proper programming language. I respect the article and the efforts of the author, but I feel that it is the past. I mastered Python a bit and the ability to just use things like dictionaries, proper parsing libraries and such, instead of kilometers of fragile pipes, it is so much better. I understand something like Python may feel total overkill, but that 10 line shell script suddenly needs quite a bit of error handling and some other features and before you know it, you wish you started out with python or something similar. [0]: https://github.com/louwrentius/ppss https://github.com/louwrentius/ppss
- gjvc 5y agodoes this do the same as https://www.gnu.org/software/parallel/ https://www.gnu.org/software/parallel/ ?
- memco 5y agoInteresting idea. I have thought about doing the trap cleanup but found it cumbersome to reason about when there are many functions so this is helpful. I would like to have seen a complete example at the end rather than just explaining why it's cool and then leaving it to the reader to imagine what it looks like. Besides cleanup, one thing I think I would love to see is a good mechanism for logging. I have started to build a file for functions and then other files, which source that as a library and calls the functions as needed. I would love to be able to tell the library functions to log something if the parent file wants it, print to stderr or stdout by default or be silent if the caller wants that instead.
- anardil 5y agoYou can take this even further by rewriting bash functions at runtime if you like. `declare` gives you direct access to the function body https://www.anardil.net/2018/dynamic-shell-scripting.html https://www.anardil.net/2018/dynamic-shell-scripting.html (self plug)
- travisbhartwell 5y agoWoah, this is very cool. I may try to adopt this. I recently discovered, similar to the author of the post for this thread, that local variables are dynamically scoped. I have been writing a lot more shell scripts lately, using a "library" [1] of sorts I've been writing. When I was debugging one of my scripts that uses mycmd, I discovered that I had failed to declare some of my variables local and they were leaking out to the global scope. I had recently added functionality to call a set of functions on script exit, so I added something that would output the defined variables, in hopes that I could write something that will output them at the beginning and then the end and show the difference. I was surprised when variables defined in my dispatch function [2] for those at exit functions were showing up, even though they were definitely defined as local. It was then that I dug around and discovered the dynamic scope of variables. I've been trying to figure out how to accomplish what I desire but exclude those variables from calling functions. I haven't been able to find an obvious way to see if the variable is coming from a calling function. I might be able to use techniques like you've pointed out in your linked post to add the tracing that I want. Still need to think more on this. --- [1] https://github.com/travisbhartwell/mycmd https://github.com/travisbhartwell/mycmd [2] https://github.com/travisbhartwell/mycmd/blob/main/shell/mycmd-lib#L212-L236 https://github.com/travisbhartwell/mycmd/blob/main/shell/myc...
- RNCTX 5y agoI have used bash to write an OCR processor that called a python wrapper around tesseract, and then turned the pdf output into json to go into a solr search database by parsing the output with sed. No, it wasn't smart to do so. Yes, it still works. No, I don't know how it works.
- Xophmeister 5y agoHere's an interesting bit of...abuse :) Since Bash is effectively stringly-typed, it can be used as a functional programming language, with pipes similar to function composition. e.g.: wtfp.sh #!/usr/bin/env bash map() { local fn="$1" local input while read -r input; do "${fn}" "${input}" done } reduce() { local fn="$1" local init="$2" local input local output="${init}" while read -r input; do output="$("${fn}" "${output}" "${input}")" done echo "${output}" } filter() { local fn="$1" local input while read -r input; do "${fn}" "${input}" && echo "${input}" done } add() { echo $(( $1 + $2 )) } increment() { echo $(( $1 + 1 )) } square() { echo $(( $1 * $1 )) } even() { return $(( $1 % 2 )) } sum() { reduce add 0 } map increment | map square | filter even | sum ...then: $ printf "%s\n" 1 2 3 4 5 | ./wtfp.sh 56
- dllthomas 5y agoI enjoyed how my bash 2048 came out: https://github.com/dlthomas/bash2048/blob/master/2048.sh https://github.com/dlthomas/bash2048/blob/master/2048.sh
- heavyset_go 5y agoThis is the pipe mill[1] pattern. As you say, you can use it to mimic function composition from a functional paradigm. It can make for some elegant solutions to dealing with streams of data. The issue is that pipe mills are very slow. $ mill() { while read -r line; do echo $line; done } $ export FIVE_MEGS=$(( 5 * 1024 ** 2 )) $ time yes | mill | pv -S -s "$FIVE_MEGS" > /dev/null 5.00MiB 0:00:23 [ 221KiB/s] [============>] 100% real 0m23.084s user 0m14.121s sys 0m26.780s $ time yes | pv -S -s "$FIVE_MEGS" > /dev/null 5.00MiB 0:00:00 [6.55GiB/s] [============>] 100% real 0m0.005s user 0m0.000s sys 0m0.006s Even Python loops are faster. $ export PYLOOP="from sys import stdin for line in stdin: print(line)" $ time yes | python3 -c "$PYLOOP" | pv -S -s "$FIVE_MEGS" > /dev/null 5.00MiB 0:00:00 [67.1MiB/s] [============>] 100% real 0m0.082s user 0m0.071s sys 0m0.019s [1] https://en.wikipedia.org/wiki/Pipeline_(Unix)#Pipemill https://en.wikipedia.org/wiki/Pipeline_(Unix)#Pipemill
- rackjack 5y agoAs stated: posix compliant functions with local variables can be done with something like: foo () ( x="hello"; echo $x ) because this creates a subshell. Fun!
- hyperupcall 5y agoI'm quite happy to see that something Bash-related is on Hacker News! Unfortunately it seems that I don't really agree with much the author... While I do agree that it would be nice to be able to have 'local' functions and have inter-function cleanup work better, the logical conclusion for me was not to use function subshells. Since the use case is for larger programs (where different functions may want to have their own cleanup mechanisms), I'm opting to go for more of a library route. For example, I'm working on a Bash library that includes a function to allow different sources to add (and remove) functions to the same `TRAP`. A similar function may be useful, possibly involving the `RETURN` trap and the `-T` flag for the use case the author brings up. Obviously, using a package manager for _Bash_ of all languages brings in a lot of overhead, but I think it can be quite powerful, especially with a potential "Bundle" feature that makes scripts work without the package manager. Concerning specifically the use of subshells, (as other commenters have pointed out) it significantly reduces performance. I also disagree that dynamic scoping is necessarily bad for Bash. I find it quite useful when I need to use various common functions to manipulate a variable - since modifying and 'returning' variables from a function is usually either slow or verbose with Bash. Admittedly though, this feature is quite annoying at times - for example, most public functions in my Bash package manager[2] all have their variables prefixed with two underscores - because they `source` all the shell scripts of all package dependencies - so I want to be extra certain nothing weird happens [1] https://github.com/hyperupcall/bash-core/blob/a17ab0a8b6070f8971a13680dfdbf5cdabf6e34d/pkg/lib/public/bash-core.sh#L28 https://github.com/hyperupcall/bash-core/blob/a17ab0a8b6070f... [2] https://github.com/hyperupcall/basalt/blob/main/pkg/lib/public/basalt-global.sh https://github.com/hyperupcall/basalt/blob/main/pkg/lib/publ...
- spicyramen 5y agoWe used to have very long shell scripts and recently I refactor most of them to use functions and shellcheck in our presubmit. This has greatly helped catching bugs and improving readability
- andygrd 5y agoBash is completely overlooked in technical interviews, at least the ones I've been involved with. But once in the role you'd find bash scripts keeping the lights on behind the scenes.
- agustif 5y agoI would rather use TypeScript and the oclif framework (what heroku-cli uses under the hood) to build any cli-tools I might need... The other day I just made a sample stripe-jobs cli app with it and playwright.