It is impossible to write a safe shell script that does automatic error checking while using the features the language claims are available to you.
Here’s a script that uses real language things like a function and error checking, but which also prints “oh no”:
set -e
f() {
false
echo oh
}
if f
then
echo no
fi
set -e is off when your function is called as a predicate. That’s such a letdown from expected- to actual-behavior that I threw it in the bin as a programming language. The only remedy is for each function to be its own script. Great!
In terms of sh enlightenment, one of the steps before getting to the above is realizing that every time you use “;” you are using a technique to jam a multi-line expression onto a single line. It starts to feel incongruous to mix single line and multi line syntax:
# weird
if foo; then
bar
fi
# ahah
if foo
then
bar
fi
Writing long scripts without semicolons felt refreshing, like I was using the syntax in the way that nature intended.
Shell scripting has its place. Command invocation with sh along with C functions is the de-facto API in Linux. Shell scripts need to fail fast and hard though and leave it up to the caller (either a different language, or another shell script) to figure out how to handle errors.
Here’s a script that uses real language things like a function and error checking, but which also prints “oh no”:
set -e is off when your function is called as a predicate. That’s such a letdown from expected- to actual-behavior that I threw it in the bin as a programming language. The only remedy is for each function to be its own script. Great!In terms of sh enlightenment, one of the steps before getting to the above is realizing that every time you use “;” you are using a technique to jam a multi-line expression onto a single line. It starts to feel incongruous to mix single line and multi line syntax:
Writing long scripts without semicolons felt refreshing, like I was using the syntax in the way that nature intended.Shell scripting has its place. Command invocation with sh along with C functions is the de-facto API in Linux. Shell scripts need to fail fast and hard though and leave it up to the caller (either a different language, or another shell script) to figure out how to handle errors.