Like programming in bash
Like programming in bash
Like programming in bash
PSA: Run ShellCheck on your shell scripts. It turns up a shocking number of programming errors. https://www.shellcheck.net/
Thank you for this. About a year ago I came across ShellCheck thanks to a comment just like this on Reddit. I also happened to be getting towards the end of a project which included hundreds of lines of shell scripts across dozens of files.
It turns out that despite my workplace having done quite a bit of shell scripting for previous projects, no one had heard about Shell Check. We had been using similar analysis tools for other languages but nothing for shell scripts. As you say, it turned up a huge number of errors, including some pretty spicy ones when we first started using it. It was genuinely surprising to see how many unique and terrible ways the scripts could have failed.
I wish it had a more comprehensive auto correct feature. I maintain a huge bash repository and have tried to use it, and it common makes mistakes. None of us maintainers have time to rewrite the scripts to match standards.
I honestly think autocorrecting your scripts would do more harm than good. ShellCheck tells you about potential issues, but It's up to you to determine the correct behavior.
For example, how could it know whether cat $foo
should be cat "$foo"
, or whether the script actually relies on word splitting? It's possible that $foo
intentionally contains multiple paths.
Maybe there are autofixable errors I'm not thinking of.
FYI, it's possible to gradually adopt ShellCheck by setting --severity=error
and working your way down to warnings and so on. Alternatively, you can add one-off #shellcheck ignore SC1234
comments before offending lines to silence warnings.
Then you’ll have to find the time later when this leads to bugs. If you write against bash while declaring it POSIX shell, but then a random system’s sh
doesn’t implement a certain thing, you’ll be SOL. Or what exactly do you mean by “match standards”?
Regex
Edit: to everyone who responded, I use regex infrequently enough that the knowledge never really crystalizes. By the time I need it for this one thing again, I haven't touched it in like a year.
You get used to it, I don't even see the code—I just see: group... pattern... read-ahead...
Most of regex is pretty basic and easy to learn, it's the look ahead and look behind that are the killers imo
(?=)
for positive lookahead and (?!)
for negative lookahead. Stick a <
in the middle for lookbehind.
Don't let the gatekeepers keep you out. This site helps.
Nice! This is the one I use: https://regexr.com/
Though it appears to be very similar on the face of it.
You always forget regex syntax?
I've always found it simple to understand and remember. Even over many years and decades, I've never had issues reading or writing simple regex syntax (excluding the flags and shorthands) even after long regex breaks.
twitch
This is one of the best uses for LLM’s imo. They do all my regex for me.
No. Learn it properly once and you're good. Also it's super handy in vim.
interns gonna intern
I just use the regex101 site. I don't need anything too complicated ever. Has all the common syntax and shows matches as you type. Supports the different languages and globals.
For me I spent one hour of ADHD hyper focusing to get the gist of regex. Python.org has good documentation. It’s been like 2 years so I’ve forgotten it too lol.
Bash was the first language I learned, got pretty decent at it. Now what happens is I think of a tiny script I need to write, I start writing it in Bash, I have to do string manipulation, I say fuck this shit and rewrite in Python lol
Ever since I switched to Fish Shell, I've had no issues remembering anything. Ported my entire catalogue of custom scripts over to fish and everything became much cleaner. More legible, and less code to accomplish the same things. Easier argument parsing, control structures, everything. Much less error prone IMO.
Highly recommend it. It's obviously not POSIX or anything, but I find that the cost of installing fish on every machine I own is lower than maintaining POSIX-compliant scripts.
Enjoy your scripting!
If you're going to write scripts that requires installing software, might as well use something like python though? Most Linux distros ship also ship with python installed
A shell script can be much more agile, potent, and concise, depending on the use case.
E.g. if you want to make a facade (wrapper) around a program, that's much cleaner in $SHELL
. All you're doing is checking which keyword/command the user wanted, and then executing the commands associated with what you want to achieve, like maybe displaying a notification and updating a global environment variable or something.
Executing a bunch of commands and chaining their output together in python is surely much more cumbersome than just typing them out next to each other separated by a pipe character. It's higher-level. 👍
If it's just text in text out though, sure, mostly equivalent, but for me this is rarely the use case for a script.
I love fish but sadly it has no proper equivalent of set -e
as far as I know.
; or return;
in every line is not a solution.
I wish I could but since I use bash at work (often on embedded systems so no custom scripts or anything that isn't source code) I just don't want to go back and forth between the two.
Yeah, using one tool and then another one can be confusing at times. 😅
It's the default on CachyOS and I've been enjoying it. I typically use zsh.
Yeah I also went bash -> zsh -> fish. Zsh was just too complicated to configure for my taste. Couldn't do it, apart from copy pasting stuff I didn't understand myself, and that just didn't sit right.
I've been meaning to check out fish
. Thanks for the reminder!
Happy adventuring! ✨
I switched to fish a while back, but haven't learned how to script in it yet. Sounds like I should learn
Give it a shot after reading through the manual! (Extremely short compared to bash's!) It's a joy in my opinion. ☺️👌
I still have to look up the exact syntax of ifs and whiles.
I've coded in bash for a while
Clearly you don't write enough bash scripts.
Or scripts for basically any other variant of the Bourne shell. They are, for the most part, very cross compatible.
That's the only reason I've ever done much of anything in shell script. As a network administrator I've worked many network appliances running on some flavor of Unix and the one language I can count on to be always available is bash. It has been well worth knowing for just that reason.
When I bash my head into a wall, does that count?
Only if you scripted it
Enough is enough
I've had enough of these motherfucking scripts on this motherfucking PC!
every control structure should end in the backwards spelling of how they started
Once you get used to it it is kind of fun.
Shame about do
though.
it could have been not
since there's no try
.
I don't normally say this, but the AI tools I've used to help me write bash were pretty much spot on.
Yeah, an LLM can quickly parrot some basic boilerplate that's showed up in its training data a hundred times.
For building a quick template that I can tweak to my needs, it works really well. I just don’t find it to be an intuitive scripting language.
If When the script gets too complicated, AI could also convert it to Python.
I tried it once at least, and it did a pretty good job, although I had to tell it to use some dedicated libraries instead of calling programs with subprocess.
There's always the old piece of wisdom from the Unix jungle: "If you write a complex shellscript, sooner or later you'll wish you wrote it in a real programming language."
I wrote a huge PowerShell script over the past few years. I was like "Ooh, guess this is a resume item if anyone asks me if I know PowerShell." ...around the beginning of the year I rewrote the bloody thing in Python and I have zero regrets. It's no longer a Big Mush of Stuff That Does a Thing. It's got object orientation now. Design patterns. Things in independent units. Shit like that.
I initially read "UNIX jungle" as "UNIX jingle" and thought I had been really missing out!
You have, look up the SuSE songs.
That's why I use nushell. Very convenient for writing scripts that you can understand. Obviously, it cannot beat Python in terms of prototyping, but at least I don't have to relearn it everytime.
So the alternative is:
We have someone at work who uses it and he's constantly having tooling issues due to compatibility problems, so.. yeah.
I'm sure it's fine for sticking in the shebang and writing your own one-off personal scripts, but I would never actually main it. Too much ecosystem relies on bash/posix stuff.
i used powershell, and even after trying every other shell and as a die hard Linux user I've considered going back to powershell cause damn man
I am a huge fan of using PowerShell for scripting on Linux. I use it a ton on Windows already and it allows me to write damn near cross-platform scripts with no extra effort. I still usually use a Bash or Fish shell but for scripting I love being able to utilize powershell.
Yeah. The best way to write any bash
script is:
apt/yum install PowerShell; pwsh script.ps1
Wait im not the only one? I think i relearned bash more times than i can remember.
Today I tried to write bash (I think)
I grabbed a bunch of commands, slapped a bunch of "&&" to string them together and saved them to a .sh file.
It didn't work as expected and I did not, at all, look at any documentation during the process. (This is obviously on me, I'll try harder next time)
I try to remember to use man when learning a new command/program. And I almost always half-ass it and press the search button immediately to find whatever flag i need.
Remember to make the .sh file executable with chmod +x
Meh. I had a bash job for 6 years. I couldn't forget it if I wanted to. I imagine most people don't use it enough for it to stick. You get good enough at it, and there's no need to reach for python.
No, Makefile syntax is more extreme.
Sure, but bash is more relatable, I think
I swapped from Make to Just: https://github.com/casey/just
Way better, IMO. Super simple logic, just as flexible.
I find Makefile
isn't too bad, as long as I can stay away from automake
and autoreconf
.
to be honest I agree and thought we would be using something more intuitive by now
Everything is text! And different programs output in different styles. And certain programs can only read certain styles. And certain programs can only convert from some into others. And don't get me started on IFS
.
I think the cool kids are using Nu now
Unironically love powershell
For a defacto windows admin my Powershell skills are...embarrassing lol but I'm getting there!
And I thought I was the only one… for smaller bash scripts chatGPT/Deepseek does a good enough job at it. Though I still haven’t tried VScode’s copilot on bash scripts. I have only tried it wirh C code and it kiiiinda did an ass job at helping…
AI does decently enough on scripting languages if you spell it out enough for it lol, but IMO it tends to not do so well when it comes to compiled languages
I've tried Python with VScode Copilot (Claude) and it did pretty good
Maybe applies more to regex, the write only language.
Back when I did a lot of Perl, those were okay-ish to parse. Nowadays, not so much. I guess it's like Bash. If you write a lot of it (maybe some people do), it's probably simple. If it's only once every six months or less, eeehhh...
It all boils down to familiarity, which comes from repetitiveness.
Knowing that there is still a bash script i wrote around 5 years ago still running the entirety of my high scool lab makes me sorry for the poor bastard that will need to fix those hieroglyphs as soon as some package breaks the script. I hate that i used bash, but it was the easiest option at the time on that desolate server.
Bash scripts survive because often times they are the easiest option on an abandoned server
So true. Every time I have to look up how to write a bash for loop. Where does the semicolon go? Where is the newline? Is it terminated with done
? Or with end
? The worst part with bash is that when you do it wrong, most of the time there is no error but something completely wrong happens.
It all makes sense when you think about the way it will be parsed. I prefer to use newlines instead of semicolons to show the blocks more clearly.
for file in *.txt do cat "$file" done
The do
and done
serve as the loop block delimiters. Such as {
and }
in many other languages. The shell parser couldn't know where stuff starts/ends.
Edit:
I agree that the then
/fi
, do
/done
case
/esac
are very inconsistent.
Also to fail early and raise errors on uninitialized variables, I recommend to add this to the beginning of your bash scripts:
set -euo pipefail
Or only this for regular sh scripts:
set -eu
-e
: Exit on error
-u
: Error on access to undefined variable
-o pipefail
: Abort pipeline early if any part of it fails.
There is also -x
that can be very useful for debugging as it shows a trace of every command and result as it is executed.
set -euo pipefail
Fun fact, if you’re forced to write against POSIX shell, you aren’t allowed to use these options, since they’re not a thing, which is (part of) the reason why for example Google doesn’t allow any shell language but bash, lol.
I can only remember this because I initially didn't learn about xargs
--- so any time I need to loop over something I tend to use for var in $(cmd)
instead of cmd | xargs
. It's more verbose but somewhat more flexible IMHO.
So I run loops a lot on the command line, not just in shell scripts.
The sad thing is that even chatgpt can't program in bash. I just want a simple script and every single time it just doesn't work. I always just end up saying "write this in python instead".
Python's usually the better choice anyway tbf. I know piping isn't as good, but there are so many footguns!
Nushell and Fish can be really convenient too.
I used to adhere to sh for an OpenBSD machine but I switched to python, Rust and Go for, even simple things.
Python is just as portable these days (on modern hardware, caveats, caveats).
Honestly so intuitive that I start there too unless I have a need for speed or distinct memory control. There's no job too small for a python script.
When I was finishing of my degree at Uni I actually spent a couple of months as an auxiliary teacher giving professional training in Unix, which included teaching people shell script.
Nowadays (granted, almost 3 decades later), I remember almost nothing of shell scripting, even though I've stayed on the Technical Career Track doing mostly Programming since.
So that joke is very much me irl.
My google history hits for powershell for loop is is in the dozens.
This. But Pandas and Numpy.
Pandas and Numpy and Bash.
.loc and .iloc queries are a fun syntax adventure every time
Oh my!
The older you get, the more things are like programming in bash.
Any no-SQL syntax for interacting with databases.
Me with powershell. I'll write a pretty complex script, not write powershell for 3 months, come back and have to completely relearn it.
It seems like it does stuff differently for the sake of it being different.
It's more like bash did it one way and everyone who came after decided that was terrible and should be done a different way (for good reason).
Looking right at you -eq and your weird ass syntax
if [[ $x -eq $y ]]
That was the point where I closed the bash tutorial I was on, and decided to just use python and subprocess.run()
-eq
Yeah, like infix, so between operands, but dashed like a flag so should come before arguments. Very odd.
You better not look at powershell in that case :p
I mastered and forgot almost entirely RegEx several times now
"mastered"
Mastered as in I could teach it to others, and assemble many complicated rules for many complicated patterns.
I am always impressed with folks that retain it.
I would a ton of it for a month or two, and then do nothing with it again for more than a year or more.
It takes a lot for permanent burn-in for me. That's the curse. The blessing is that I learn very quickly.
Je comprend tellement! Je répond en français pour ma première réponse sur Lemmy juste pour voir comment ça va être géré!
I so understand! Answering I. French for my first Lemmy reply just to see how it’s handled.
Realizing now that language selection is mainly for people filtering. It be cool if it auto translated for people that need it.
I don’t write very small shell scripts because I am not a job destroyer.
Incredibly true for me these days. But don't fret, shellcheck and tldp.org is all you need. And maybe that one stackoverflow answer about how to get the running script's directory
VLOOKUP. Every time. Also Catan Cities and Knights.
This is why I finally switched to nushell.
I love Nushell
I’d been considering it for awhile, but thought it wasn’t worth the trouble of switching until I realized just how often I do things the tedious manual way because writing a bash script to do it is so arcane
I feel same with regex....
Or it’s because other people are assholes. And write shit garbage. And then you go to fix a bug or add an enhancement. And then you are stuck.
Very true. Been programming/scripting in Bash since many many years, I could almost consider myself an "expert", however I still need to look up the same crap over and over again, since remembering weird symbol constellations is the last thing you should do, when you actually just wanna achieve a goal with the script and not learn how to summon the spirit of some C-related language creator.
I’ve switched to nutshell imo. Bash is in need of a replacement