Pure Bash Bible – A collection of pure bash alternatives to external processes
github.com
github.com
My thoughts on writing a Minecraft server from scratch in Bash | https://news.ycombinator.com/item?id=30347501
Bash Pitfalls | https://news.ycombinator.com/item?id=30345487
Show HN: Toolbox – A framework for modular Bash scripts | https://news.ycombinator.com/item?id=30067708
Use Bash Strict Mode | https://news.ycombinator.com/item?id=30217719
A Wordle clone in 50 lines of Bash | https://news.ycombinator.com/item?id=30174112
Bash should be considered an esoteric programming language. Shell Programming Considered Harmful.
It's hard to program, and easy to make mistakes in. It should be left as a tool of last resort.
(that said, I understand the appeal of doing weird things with it, like the Minecraft server, for the same reason other esoteric programming languages have appeal)
Ideally we should all try to more programming languages that are harder for us to shoot ourselves in the foot with, rather than easier ;-)
The problem usually come when you attempt to use it for nontrivial programming. But that just not what it's for, any more than the difficulty in building an OS kernel is a legitimate complaint against PHP.
This is important to know in the context of what you are saying.
The Algol structures in the Borne shell are the most incongruous parts of UNIX.
"I am a strong believer that Bourne-derived languages are extremely bad, on the same order of badness as Perl, for programming, and consider programming sh for any purpose other than as a super-portable, lowest-common-denominator platform for build or bootstrap scripts and the like, as an extremely misguided endeavor. As such you won’t see me spending many words on extensions particular to ksh, Bash, or whatever other shells may be popular."
Consider this:
for f in *png; do convert $f $(echo $f | sed 's/png$/webp/'); done
This is like at least a screen of code in in most languages, you get that sinking feeling where you need to fork a process and deal with its lifecycle and deal with some standard library to list files and don't forget to close the file handle for the directory and god forgive if you run a program with actual output then you need to read from a pipe. Like, geesh, do I have to write a whole program to convert a few files?In a shell, it's just something you type up because you needed to convert a few files. Don't get me wrong, shell scripts are extremely bad at most things involving non-trivial branches, long-lived state, really most things other languages are good at, but man are they ever good at some things most programming languages are bad at.
lee@sp3tmp1:ls *.png
'a b.png' c.png
lee@sp3tmp1:for f in *png; do convert $f $(echo $f | sed 's/png$/web'); done
convert-im6.q16: unable to open image `a': No such file or directory @ error/blob.c/OpenBlob/2924.
convert-im6.q16: no decode delegate for this image format `' @ error/constitute.c/ReadImage/575.
convert-im6.q16: unable to open image `b.png': No such file or directory @ error/blob.c/OpenBlob/2924.
convert-im6.q16: unable to open image `b.png': No such file or directory @ error/blob.c/OpenBlob/2924.
convert-im6.q16: no decode delegate for this image format `' @ error/constitute.c/ReadImage/575.
convert-im6.q16: no images defined `b.webp' @ error/convert.c/ConvertImageCommand/3229.
[etc.]I think you could be making a more complicated point.
for f in *.png; do convert "$f" "${f/%.png/.webp}" ; done
Quoting the arguments lets it correctly handle file names with funny characters, including spaces. Using the `${parameter/pattern/string}` parameter substitution means the shell does all the work itself without invoking an external command (other than convert, of course). The '%' in the parameter substitution requires the pattern to match at the end, so "foo.png.png" becomes "foo.png.webp" and not "foo.webp.png" -- an unlikely corner case, but you might as well do it right. ("foo.png.blah" doesn't match "*.png" in the first place.)For elaborate commands like this, I typically run it once with an "echo" inserted ("echo convert ..."), confirm that the resulting commands make sense, and then hit up-arrow to edit the command and delete the echo.
https://www.gnu.org/software/bash/manual/html_node/Shell-Par...
You should script defensively, for when this is run on Windows or elsewhere [maybe Android] that will break this assumption.
Newlines can also be part of a filename. For extreme rigor, use find -print0 and xargs -0.
I have covered some of this here:
https://www.linuxjournal.com/content/parallel-shells-xargs-u...
(Somebody took me to the Hacker News front page for this, and nobody said that I made a mistake.)
I think you are missing the point. I wouldn't run a shellscript on Windows or any other place than the terminal I entered it into. It's an expression of something I want to do at that particular time in that particular directory.
The entire point of my post is that if I wished to write something portable and robust, I wouldn't use bash in the first place. That's not what bash is good at. But quick one-offs, holy crap is it good at that.
The most straightforward POSIX shell on Windows is the Busybox port, which uses the Almquist shell (ash) with many bashisms reintroduced.
This is said every time Bash scripting is mentioned. Why people can't get into the habit of quoting all variables in Bash is beyond me and the mention of white space makes sense; but how often, if ever, have you encountered a file name that contained a newline?
Most of the Unix tools are line oriented by default anyway and are frequently used to manipulate lists of file names and paths.
All else should be quoted, and newlines can happen, primarily from abuse. Do not trust user input!
Calling fopen() on a file with every ASCII character will work on POSIX, as long as it does not contain a null or forward slash (/). Coding defensively means that this does not crash your processing.
I was objecting to the knee jerk inclusion of warnings against file names including newlines. Has anyone encountered one in the wild that was not itself an error?
>> Consider this:
> for f in *png; do convert $f $(echo $f | sed 's/png$/webp/'); done
This is buggy, and it actually represents exactly the problem with Bash scripting.
quick: without looking anything up, write something in bash that takes a string of comma-separated values and turns it into an array of those values.
then check to see if your answer is on this very long list of wrong implementations:
I would just use Python, where strings are sane and lists are sane: my_string.split(", "), boom, done, no jumpscares.
I disagree. Bash is fine. Nothing esoteric about it.
> It's hard to program, and easy to make mistakes in. It should be left as a tool of last resort.
It's easy to program, but it has a learning curve. Use shellcheck. It's OK to go first to bash if you need a shell script. Other languages make pretty crappy shell scripts.
Arrays:
- `${#myvar[@]}`: unreadable
- `mapfile myvar < <(grep pattern file)`: "mapfile" is not exactly a clear term (there's the synonym
"readarray", but "mapfile" is the reference; worse, you may find both used inconsistently); the
command as I wrote it also has two problems
Strings: - `${myvar##.*}`: unreadable
- `echo $(IFS=,; echo "${myvar[*]}")`: unreadable; most also don't know the difference between `[@]`
and `[*]`; this doesn't also work for two-char join operations
- `[[ $myvar =~ $(echo '\bpattern\b') ]]`: unreadable, and most don't know why command substitution
is needed
Redirections: - `3>&2 2>&1 1>&3`: most don't know what this meansThe main issue is that many people try (by necessity or not) to cobble scripts together without really learning the language and its idioms. It's not that hard to really learn it though, it's basically one man page then the mandatory [wooledge wiki][1].
It may be much easier (and most of the time I would generally prefer) to use Python for scripting purposes, but Bash is a) almost always available and b) widely portable.
If you manage any servers where you never know if Python is available or if it’s version 2 or 3 (and you have no power to change this for one reason or other), you know the value of this. No, it’s not ideal, but we live in a non-ideal world. Long live Bash.
And when you consider there really isn't a standard library, mostly gee-I-hope-this-UNIX-util-is-installed...
For example, I'm working on a Hashicorp Vault server install and due to it's sensitive nature, I'm strongly considering using bash to set it up over something like python. I love the ability to test in a robust language, but the extra dependencies are hard to justify, at least on a security sensitive application.
Well, we "write" one-liner programs with it all day every day - since it's the shell.
I'm not saying bash doesn't have a bunch of warts, but - what other shell language would you suggest as an alternative to it?
Don't get me wrong, I have nothing against fun and creative projects. If someone wants to script something complicated in bash for the lulz, the challenge, to learn something, or just to show off bash-skills, I'm all for it.
What I am against, is when I get asked to debug a 2000 LOC system used in production that was thrown together in bash, waste 2 days on it, only to end up doing what should have been done in the first place, and rewrite the damn thing in 200 lines of Python or 400 lines of Go.
It can, and should, be used to automate some things, string some commands together, make certain tasks easier. I use and write bash scripts in my daily work, and make my life easier with it.
But there comes a point, and that is sooner rather than later, when something should no longer be written in bash, but in a language that wasn't designed primarily as a command line interpreter. Can I make large complicated systems in bash? Sure. Can I carve the handle of a hammer so that it can be used as a screwdriver? I'm sure someone more skilled in woodworking than me could do it. But sometimes the question isn't if it can be done, but if it should.
Shell scripts to automate processes with other tools is exactly what they are designed for, and adding in other logic and loops is fine too, but if you are setting out to create what would be considered a full program rather than an automated task you should definitely consider alternatives (of which there are several suitable choices) that usually end up being easier to maintain.
It used to be that the main alternative was perl, but frankly that was/is no better (IMO much worse) than bash for encouraging the generation write-only (difficult to maintain) code. Python is often a good option, and I've seen node used, though these don't have the ubiquity that sh/bash does (or perl used to have) which is one advantage of bash: it is almost everywhere, even Windows these days (or stick with core posix sh and you'll find support a little wider again), though maybe without some of the supporting externals which is when tricks like these come in.
If you are writing some simple automation, or maybe slightly less simple, then bash is fine as a go-to, but if you are setting out to write something complex bash is a bad choice unless compatibility with many environments you can't dictate have another interpreter present is a non-negotiable requirement.
There is the grey area when a script, or collection of scripts, becomes a larger program/environment over time. Sometimes the effort to rewrite (and fully test) in another environment is not worth the small benefit of doing so, and is therefore a bad use of developer/admin time that could be used elsewhere, particularly when high performance is not an important feature. Though if you find yourself with a lot of bash script, do yourself (and your later replacement when you've moved on to newer projects) a massive favour and make sure it is well documented even if that is only in in-script comments.
The entire point of Bash/Shell scripting is (or darn it, ought to be) to use it to string together OTHER programs to get stuff done. "Pure Bash" to me is like a bar of soap that never gets wet.
Pure bash solutions avoid these problems, and can be just as simple as (or simpler than) an alternative that use external tools.
https://en.wikipedia.org/wiki/The_purpose_of_a_system_is_wha...
Prescriptivism is perhaps helpful when starting out on a project and you need to prune down a vast tree of possibilities, but once you already have a thing, prescriptivist declarations are pretty impotent at helping you understand how that thing works.
If your bash script has some tight loop, calling out to external tools can incur a huge performance overhead. Rewriting in bash can aleviate that. How do you re-write it in bash? Well... this article provides good fodder for thought!
> like a bar of soap that never gets wet.
Here are some uses of soap that would be hampered by it getting wet:
- Make-shift lubricant on that sticky cabinet drawer
- Draw temporary markings, like a crayon
- Potpourri alternative
- Fragrant seal on your letters
- Deterrent to puppies chewing on your chair legs
On the same hardware, Windows is 100x slower at forking an external process.
When you are using a (POSIX) shell on Windows, don't cause a fork, especially in a loop.
Do everything internally in a POSIX shell on Windows, unless an enormous time penalty is acceptable.
But if I'm getting a tad meta, I think there is generally enough of what you're doing (experts really hacking at things to push their limits) and not enough of what I think Bash/scripting could provide -- namely non-experts discovering "coding" NOT through the typical "start with a real language and do hello world" and instead through, "Here's bash; it's for stringing together other programs to do stuff."
Use #!/usr/bin/env bash instead of #!/bin/bash.
The former searches the user's PATH to find the bash binary.
The latter assumes it is always installed to /bin/ which can cause issues.
And the former assumes that `env` is installed in `/usr/bin`, so I am trading one assumption for another.But, in all seriousness, you're right - you're making a trade. The question is which side of the trade is more portable. I use NixOS which doesn't have bash in /bin. So, I've had to ask people on my team to replace the hashbang. The /usr/bin/env hashbang has yet to fail on any machine so, anecdotally, it seems more portable.
This isn't me ranting against systems with new ideas about file system layout, this is just me being pragmatic: When it works on all my work-, private- and production-machines, I see no reason to run an extra binary in front of all my shellscripts.
If something works for X% of people and a trivial change makes it work for Y% of people (Y > X) then I advocate for making that trivial change.
1 year ago https://news.ycombinator.com/item?id=24827360
2 years ago https://news.ycombinator.com/item?id=21013150
Things like the above motivated me to create Next Generation Shell.
Edit: hint - yes branch, no branch, exception.
More about motivation: https://ilya-sher.org/2020/10/31/bash-or-python-the-square-p...
Project: https://github.com/ngs-lang/ngs
trim_string() {
# Usage: trim_string " example string "
: "${1#"${1%%[![:space:]]*}"}"
: "${_%"${_##*[![:space:]]}"}"
printf '%s\n' "$_"
}
You may be interested in Elvish (https://elv.sh), which simply has a builtin function for trimming strings: https://elv.sh/ref/str.html#str:trim-space trim_string () (
x=${1%[:space:]}
return ${x#[:space:]}
)
Note the use of a subshell ( instead of command grouping { because POSIX shells do not have local function variables.At least, I think that would work.
On Windows, forking is expensive, so I wouldn't do it this way.
cp /dev/null file
Test if a port is listening without telnet:
echo > /dev/tcp/address/port && echo Yes || echo No
That's not actually a file. It's just a path Bash recognizes and is the interface to socket functionality. udp works too.
That destroys a file, making it 0 bytes. It doesn't touch a file, not at all.
"touch" exists for a reason.
The actual use case touch was designed for was to update the timestamp of a file. This is a huge case for developers, since timestamps are used in dependency resolution of partial compilation. [1]
[1] https://man7.org/linux/man-pages/man1/touch.1.html
NAME
touch - change file timestamps
DESCRIPTION
Update the access and modification times of each FILE to the
current time. trim_string() {
# Usage: trim_string " example string "
: "${1#"${1%%[![:space:]]*}"}"
: "${_%"${_##*[![:space:]]}"}"
printf '%s\n' "$_"
}Sometimes, it's genuinely better to plug on in shell (e.g. if you are just calling other scripts and chaining stuff), but, especially if you want some less-magical string or list manipulations, often Python/Perl will provide a more readable, more maintainable, more _testable_ script. YMMV with Perl.
“Learn how to write routines like this and make them readable” seems like it’s not the point of this “Bible”.
I’m not against readable code by any means (maybe there’s even a cleaner way to write this) but it seemed inconsequential in my opinion.
> insert quote about writing your code as if the person who will have to maintain it next is a violent psychopath who knows where you live
Why do we want to adhere to POSIX?
$ man bash | grep slow
It's too big and too slow.
$ rpm -qi dash | tail -3
DASH is a POSIX-compliant implementation of /bin/sh that aims to be as small as
possible. It does this without sacrificing speed where possible. In fact, it is
significantly faster than bash (the GNU Bourne-Again SHell) for most tasks.
So let's find out how this function works in dash. $ ./testtrim
./testtrim
$ sed -i 's/dash/bash/' testtrim
$ ./testtrim
foo bar
I think I will pass.The two important places for portability are Ubuntu's /bin/sh (which is dash, not bash), and the Busybox shell.
Commercial unix would be important, but is likely a distant 3rd by the numbers.
But... Why? During my professional career of about 10 years, and even before that, I've not once had to require POSIX compatibility for any of the shell scripts I've written or come across. The few times I had a snippet that couldn't run I have been able to install bash 4+ with ease.
I'm sure there are times where POSIX is kind of needed, but it's becoming exceedingly rare.
I recently rewrote this script, so it would run on Windows, via Busybox ash. It needed quite a few changes. I've become somewhat practiced on the removal of bashisms.
Oddly enough I had to put a few back. Busybox on Windows doesn't implement stty that I needed to read a password, but it did have read -s, so I used that instead. I threw several snippets of ash-emulated bash back in, that would never ever run on dash.
When you ask "but why?" this is precisely why - I need this functionality in a specific place, where you cannot go.
I got in the habit of at least gesturing towards POSIX back when it was more common to run a bunch of different unixes. And I still run both FreeBSD and Linux at home, so there's value there for me.
Mostly, I still do it because I'm always surprised by which artifacts I create end up being long-lived, and you never know what will be valuable in the future. One of the things I'm technically proudest of ended up only being useful for less than a year, whereas I know a dumb 4 line hack I wrote on a contract in 2002 is still running via cron every night, now on a VM in AWS.
Microsoft was pivotal in the formation of the standard, as Korn was required to run in a 64k text segment for Xenix, and this was retained for POSIX.2.
The parser for the Borne family is very complex, and cannot be implemented with a yacc grammar. There is some value in starting again with something less convoluted.
This guy tried to implement a POSIX shell in OCaml, and he is rather perturbed with the entire Borne family (I wish I knew parsers this well):
https://m.youtube.com/watch?v=fiJR4_059HA
Bash has a number of real strikes against it... GPLv3 - which caused Apple to dump it, speed - which caused Debian/Ubuntu to demote it, and the lingering damage bashisms and their damage to portability.
Yes, because it says it trims strings, but is otherwise unreadable to most people. If they have a bug in their script caused by this function not working correctly, good luck finding it.
if [ -z "$foo" ]
then :
else echo not blank "$foo"
fiI often use it instead of truncate or touch
: > somefile
: >> somefile
: is not lexically special (the way # is), you can use : in variable and function names, even create a function called just ":" if you're trying to confuse...
I mean it's parameter expansion, just flip down to that section of the manpage, and then there is posix regex in there. Not too difficult to look up in the manpages.
And my bash code would probably be more readable if I started collecting common operations in a function library rather than repeating the same sed/awk incantations that aren't super readable. At that point might as well use pure bash/sh implementations to save spawning a new process when reasonable.