291 points · by rrampage · 4y ago · 96 comments
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)
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.
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.
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."
Pure bash solutions avoid these problems, and can be just as simple as (or simpler than) an alternative that use external tools.
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' "$_"
}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.
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...
“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.
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.
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.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.
> 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
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.
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.