[GTALUG] Script to show HTTP(S) and TLS details for a website
D. Hugh Redelmeier
hugh at mimosa.com
Mon Aug 12 12:39:06 EDT 2019
| From: William Park via talk <talk at gtalug.org>
| 1. You don't need quotes in variable assignments like
| var="$(...)"
| var="$var1"
True. Even if var1 has whitespace. But the quotes are harmless.
The rule I aspire to following:
Quote all shell variable references EXCEPT when they must not
be quoted (rare).
It's a lot easier than knowing the very odd rules applying to
assignment and other special contexts.
Why is assignment odd? Because, syntactically, it is a kind of word
(an ASSIGNMENT_WORD according to POSIX).
| 2. The following tests are the same. They both tests if var is empty.
| [ "$var"x = x ]
| [ -z "$var" ]
I like -z
Superstitiously, I would write
[ "x$var" = x ]
instead of
[ "$var"x = x ]
I would otherwise worry that if $var started with, say, -, funny
things might happen.
| 3. Testing if command succeeded or failed can be done in-line.
| if command1 | command2 | command2; then
| ...
| else
| ...
| fi
When I learned sh (long before POSIX) I think that the Bourne Shell
set the exit status of a pipeline to the exit status of the first
command. So I'm (needlessly) nervous about what the exit status of a
pipeline is.
BASH has an option to have a pipeline fail if any component fails.
Seems useful (but not portable): -o pipefail
Speaking of useful bash options, I always turn on these two options in
my BASH scripts
-e stop dead when a command returns an error in an untested
context
-u consider a reference to an undefined variable to be an
error
These catch a lot of errors that might otherwise go unnoticed.
| 4. Case statement is usually better than if statement. eg.
| if [[ "$var" == glob ]]; then
| ...
| fi
| vs
| case $var in
| glob) ... ;;
| esac
| Note the missing quotes in case, too. You don't need it.
I think that [[ ]] is a BASHism. I presume that it has advantages
over [ ] but I don't know them.
In the old days, test (AKA [ ]) wasn't built-in and so case was
faster. This isn't true of modern shells.
More information about the talk
mailing list