151 points · by RafelMri · 2y ago · 118 comments
A bash script is basically scripting what you do on your terminal. I feel like scripting in the same language that is your terminal interface is underrated.
You can basically take a look at your command history and wrap it up as a script.
Yes, bash is clunky as hell. It has some really ugly warts. But learning the basics will make you more proficient in the terminal. The synergies are really nice.
Ruby's https://github.com/ruby/shell (which used to be bundled in Ruby itself) doesn't get much mention but is much more clear and useful to me.
# system commands are not defined by default, only builtins, for safety
Shell.def_system_command 'ls'
Shell.def_system_command 'grep'
Shell.def_system_command 'jq'
Shell.new.transact do
# simple redirs just work
ls | grep('test') > 'some/file'
ls | grep('other') | tee('foo') >> 'some/file'
# pops at the end of the block
cd 'some/dir' do
# nested redir for demo
(cat < 'foo.json') | jq '.[] | { bar: .bar }'
end
end
† http://www.catb.org/esr/writings/unix-koans/ten-thousand.htm...https://pypi.org/project/plumbum/
(also supports dispatching commands to SSH sessions)
Also Ruby's Shell was part of the stdlib, so if a system had Ruby you could use it without having to go through system ruby `gem install` conundrums. I think they made a mistake unbundling that one.
Otherwise, shell scripting is nice
Example: pyinvoke/fabric https://www.fabfile.org
It also recommends wrapping variables with curly braces like ${name}, without explaining why, later on never does so itself throughout the rest of the book. There are a lot of such missing explanations in the whole book. It does make it short and fun to jump straight into the examples but i think it could benefit from some facts and reference material, at least to link to.
Anyway, seems like most people here are more interested in arguing over bash vs python than discussing the actual content. A little surprising to see this get so many points.
bash script is "okay" I guess if your "script" is just a series of commands with no control flow.
Why do that when I can literally just ``` N=0 while read -r URL; do curl "$URL" | jq '.data[].someProp' | grep -v "filter" > "$N.data" N="$((N+1))" done < ./links.txt ```
The other thing is bash makes it exceptionally easier to integrate across different system tools. Need to grab something from a remote with `rsync`, edit some exif, upload it to a CDN? That's 3 commands in a row, versus god knows what libraries, objects, and methods you need to deal with in Python.
So that other people can read and modify this.
It's very easy to read and modify if you just write it out longwise, which is what I'd always do in some actual script. (I also like to put reading data at the beginning of the pipeline, so I'd use a useless use of cat here.) To illustrate:
N=0
cat links.txt \
| while read -r URL; do
curl "$URL" \
| jq '.data[].someProp' \
| grep -v "filter" \
> "$N.data"
N="$((N+1))"
done
It's a very simple pipeline with a single loop. It's not very different from pipelines you might write to transform some data using a thread macro in Clojure, or method chaining against a collection or stream in OOP languages like Java or Scala or Ruby or whatever you like. set -euo pipefail; N=0 while read -r URL; do curl "$URL" | jq '.data[].someProp' | grep -v "filter" > "$N.data" N="$((N+1))" done < ./links.txtAlso, I've been forced to work on a huge SCons based project and I guarantee python can make your life quite miserable when used for something it's not supposed to.
A lot of originally little automation/dev scripts bloat into more complicated things as edge cases are bolted on and bash scripts become abominations in these cases almost immediately.
If you can't do it in POSIX (sh and utilities) and don't want to do an extensive investigation of portability for what you need, pony up for Python/Tcl/Perl (all in MacOS base, by the way).
The same can be said of bash, especially since you mention Alpine (also FreeBSD)
Perl, though... ;)
(if Perl is not there it gets pulled in very quickly as a dependency of something, e.g typically you pull git, you get perl)
I was looking up statically typed alternatives and stumbled upon Ammonite and Scala-CLI for scala. I haven't used them much, but Ammonite bundles some basic libraries including command line parsing, http, and json, which are probably 99% of what I used in Python too? And Scala seems like an interesting language too with decent editor integration.
What does pyright/pylance say?
Bash scripts and Bash control flow has been and is used in highly critical scripts all over the place, including other planets.
We’ve been writing reliable, well-designed scripts for many decades. Some of my scripts are several hundred lines long and older than the system engineers currently occupying their positions.
Python is fine too. Use the right tool for the right job.
Used to be a viable strategy until they started to drop modules from the standard library at every single release.
That’s a bit of a ridiculous statement, there’s a small number of very-long deprecated modules removed in 3.12, and some more recently deprecated modules in 3.13. And these things are old, largely or completely unmaintained, and usually complete obsolete.
I’d be surprised if anyone has a script that’s been adversely effected by this, and if they did it’s because they stopped maintaining it years ago (and also chose to both silence warnings and upgrade interpreter versions without reading the release notes).
Consider that the python foundation absolutely has the resources to put a developer to maintain them.
If they don't is because they don't want to.
> and usually complete obsolete
The amount of modules I've had to patch to keep working on 3.12 tells me they aren't as obscure and unused as you think they are.
> I’d be surprised if anyone has a script that’s been adversely effected by this
I'd say that over 99.9999% of python users do not download python from python.org. They use whatever is on their system. Which means that updating an LTS distribution will create mayhem. And that's considering that most modules have already been patched by the distribution maintainers to fix all the brokenness introduced by the new python version.
Also, a bash script from 30 years ago still works fine. A python script from 5 years ago doesn't start.
Instead they removed distutils, so now there is no way to install any module without using a 3rd party installer.
It seems to be quite fast, can escape UNIX-Linux idiosyncrasies and I still can see all the magic variables in the code after those years.
Maybe it’s better to just get back into Perl instead of figuring out how to pipe back to back to few applications and jq on top?
Python unfortunately doesn't shine where Perl is good at. Mostly of the command line work involves passing around adhoc text, parsing and using it.
You are better off using a language designed to do that very task than use something else.
What advantages does zx have over Python, Ruby or even Fish for example, if we're installing extra programming languages?
https://www.shellcheck.net/ is amazing to spot pitfalls.
See my list https://learnbyexample.github.io/curated_resources/linux_cli... for learning resources for CLI tools, scripting, etc.
There are many reasons to use either. Probably about as many as there are to use the other. Choose wisely.
That's a strawman though.
I don't want to have to install a "vast selection of third party modules" just so I can run `kubectl apply -f foobar/*` on my CI pipeline.
If you never run into this problem, fair enough, maybe you don't need bash.
A lot of us do.
Not that long ago, I needed to write a script that would grab the last command in a shell file that had a list of commands, add an argument or two to it, and run it. Which proceeded to barf because the command had quotes, for some of the arguments had necessary spaces in them, and I couldn't figure out the way to get the necessary string in a way that bash could properly execute the command. My eventual solution was to just use python's shlex module to parse the line and output an executable command (and remark that I should have just started the script in Python in the first place)...
It does that just fine, I don't have all the details obviously but it sounds like printf %q or ${arg@Q} is your friend here.
printf '(%s)\n' "one two" "three four five"
echo "How you doin'?"
Running: while read -r line; do
eval command=($line)
command+=("arg with spaces" "other arg")
"${command[@]}"
done < lines.txt
Yields (one two)
(three four five)
(arg with spaces)
(other arg)
How you doin'? arg with spaces other argThere's no requirement that a shell language suck as much as bash.
How do you debug it and trace it ...
I do use it as said this is the terminal command line and both Mac/Linux supported it. And if it works, it work even nohup.
Just hard.
Somewhere in the middle of every stack is a bunch of bash and makefiles. Don't replace that or avoid it. Embrace it. It's not perfect, but it's important to know.
Other things don’t: you need non-trivial bash.
I don’t mind if people do their heavy lifting in VSCode, I like the tool myself.
But if you can’t unfuck the little daemon that VSCode talks to?
You’re out of commission. You’re at the mercy of people who can.
Just curious: where exactly is the shell in `cmake -GNinja`? Or is CMake not a build system hmmm? Nevermind that some people use bazel or meson or something ... other than shell...
Shell scripts in your build system are a code smell. In cpp projects it's covering up for people that don't how to use the actually correct tool for the job: the CMake scripting language.
I’ve also been doing way more with google cloud shell. I was always such a point and click guy when it came to setting stuff up in GCP but automating and scripting with bash in cloud shell using ChatGPT is so much faster and repeatable.