Use long flags when scripting
thechangelog.com
thechangelog.com
This is an interesting conundrum. As has been pointed out, POSIX specifies standard options (which are all short):
http://news.ycombinator.com/item?id=5165058
But these are not universally supported:
http://unixhelp.ed.ac.uk/CGI/man-cgi?ps
What to do? My proposal: do what we do in the C/C++ world when presented with portability problems: abstract it away. POSIX sh supports functions, which can be named appropriately for readability, while calling the proper arguments and commands for different platforms. To avoid unnecessary duplication of platform/argument detection, setup could be done in a function called before anything else to create variables with the appropriate command names and arguments.
This may all seem too involved, but realize that we are talking about creating robust software that is to be maintained, so applying proper software engineering principles seems appropriate.
* http://en.wikipedia.org/wiki/KISS_principle
* you should adapt the way you think about programming to the language you are using. This is shell, not Ada.
So you want to write some script that will only ever run on systems with GNU utilities installed, and you never ever plan on porting it? Fine. Just do the world (and yourself) a favor and be aware of and admit that fact upfront. And if you're going to break POSIX compatibility anyway, it would be nice if you use the long options for better readability.
I'm thinking of shared dotfiles, build scripts, deploy scripts. The article you link to mentions SunOS and OSF/1. How bad are the incompatibilities on modern POSIXes only? (note: I really do not know and wouldn't know how to find out)
To compare, how many people would write a web page that supports IE5? Some would, but would you generally advice methods to make IE5-compatible pages in 2013?
Maybe we need a http://caniuse.com for Unixes.
if [ -n `command -v autossh` ]; then
function ssh_persist {
autossh -C -o "CompressionLevel 9" $@
}
else
function ssh_persist {
while true; do
ssh -C -o "CompressionLevel 9" $@
sleep 60
done
}
fi
Edit: well, as long as I'm doing this much editing, I might as well make it better. To be sure, this isn't exactly what I actually run :) But it's a fair approximation and it gets my point across.# Invoke curl in silent mode (-s), pipe the output to grep
# and use an extended regex (-E) to only show the resulting
# digits (-o: only print matching text, not the whole line):
curl -s checkip.dyndns.org | grep -Eo '[0-9\.]+'
BTW, you've probably a bug in your regexp because you like to needlessly and wrongly escape a dot without knowing the regexp syntax you're using. Assuming you don't intend
$ grep -Eo '[\.]' <<<\\
\
$
that is. :-)(curl's -s should be accompanied by -S IMHO, and it's brain-damaged in not having that behaviour under the one option.)
If you still prefer putting these hints in comments, I would rephrase your comments in a way that they are easily identifiable as useless, so I can stop reading them right away. For example:
# -s flag: puts curl in silent mode.
# -E flag: puts grep in extended regex mode.
# -o flag: prints only matching text.
curl -s thingy.thing | grep -Eo '[0-9.]+'
An additional win: comments are slightly more future proof. When the comments inevitably become outdated, you'll now see:
# -E flag: puts grep in extendex regex mode.
curl -s thingy.thing | egrep -o '[0-9.]+'
which is better because the comment is now merely irrelevant instead of actively wrong.
# Get my IP address by checking dyndns.org
curl -s checkip.dyndns.org | grep -Eo '[0-9\.]+'
When reading the script, you want to know what it does, not what each character in it does.Using long flags actually hinders that by adding clutter; you have to parse a much longer line to know what it does. Adding a functional commend and then using the clean short flags is IMHO a much better way.
# Get my IP address by checking ifconfig.me
curl -s ifconfig.me
The less work you have to do, the better :)NOTE: If you visit ifconfig.me with your browser you get an html page full of text, but with the curl useragent it just returns the ip-address
If your script contains four or five such 'less work you have to do', I bet it breaks within a year.
Alternatively, you could create a "whereami" that returns the ip, and use that in your scripts. If ifconfig.me goes down for good, you have to change the url in one place. I'm sure you'll cope.
CURL_FLAG_SILENT=s
# Then call them here:
curl -$CURL_FLAG_SILENT ifconfig.me
Short options should be used where they're the more typically known and standardised. Long options are for the unusual.
grep -iv
sed -n
tr -dc
awk -f
ls -tr
comm -23
tail -nAt the same time, for instance, I've no idea what the -tr flag to ls does, even though I use ls often enough.
BTW, a month of using Unix should have a Unix user knowing what ls's -t and -r flags do, along with -a and -l they're some of its most commonly used.
This reminds me of the whole "replace" debacle [1] a couple weeks back, where the power nerds jumped all someone who wrote a bit of code to simplify common tasks. It's hard to understand how some people think flexing their arcane knowledge in everyone's face makes them look good. They trash efforts to make software more accessible and maintainable so they can pretend to be king of a tiny hill.
1) It is not a command that someone "uses", it's a script written by a programmer to be run for a business task or an end user quite likely may not "use Unix" (by your definition) ever.
2) The script goal most likely is not to make Unix work for you - it was originally written to make Unix do task X for you; but the goal/question in the OP is how to make that program more maintainable. Maintainability is an important goal, and to achieve that it's definitely acceptable to mutilate the way you usually do one-off tasks manualy.
3) The shell script is written for non-shell-script users - it's quite likely some glue for a system where 99.9% is in other languages, and the maintenance guys will specialize in those languages, and may not "use Unix" in their daily tasks at all. It's very common and reasonable to write all your code on a Win or Mac computer and then have it deployed to some linux server; and most companies currently do have separate ops teams (which would "use Unix" every day) and developer teams, which might "use Unix" once a month or less, even if the end binaries run on Unix.
No, the source of Unix nerd's retort is the realization that a small set of simple, standardized and very sharp tools performs better over time than an ever-increasing set of intuitive tools to suit a narrow use case. This is not to disparage anyone for writing something like that replace project. You certainly don't deserve scorn for that, and if that tool finds a healthy place in your utility belt then all the better.
However if you do a lot of work with text files on unix then I think inevitably you will reach a tipping point where it is in fact easier to learn and remember a limited set of commands and flags than it is to remember the ideal mountain of simpler commands that do all the things you regularly do in a more beginner-friendly fashion. If you want to argue against "arcane" unix tools being better you have to confront this argument head-on without assuming the proponent is an insecure, anti-social neckbeard out to prove his own superiority.
This may have been true(r) twenty or thirty years ago, but in a contemporary Unix installation, it is not true at all.
The set of tools is often NOT small (there are thousands of them); they are NOT simple (two examples: 1. the ls man page and the huge number of options it takes; 2. shell quoting rules); they are NOT standardized (I regularly run into incompatibilities between BSD-derived and GNU tools, for example, the -E option for grep); and they are NOT sharp.
In summary, the whole "small tools that one thing only, but that do that one thing well" thing is a stupid, outdated mantra that may have made more sense many years ago, but not anymore. For some reason, people keep on blindly believing it even though it bears no relation to the reality of modern Unix programming.
Reading man-pages does do a lot for you. And in my experience, I don't spend a lot of time while on the same engagement/project/whatever writing shell code across BSD/solaris/GNU-linux/etc.
And honestly, if you can write a sophisticated sed substitution for BSD without reading the man page, is there really THAT big of a barrier lying between you and writing the same thing in GNU/Linux, or non-POSIX-compliant sed, or whatever else? You read the man page for 10 seconds and find the flag that means what you want to use. If it's different, you explore.
This is totally not a rant at you, and I sincerely hope you don't take it that way - I just haven't found myself utterly foiled by the differences between say, RHEL v SUSE v BSD recently. There are differences, but hell - there are differences between versions of languages, between terminal emulators (scripts that work in bash but not in zsh and vice versa), etc.
I take issue with the attitude that the way these tools are used, with their billion cryptic parameters, is some flawless pinnacle of achievement.
Some people have put a lot of effort into memorizing Unix switches already--but the difficulty doesn't mean that work was meaningful. Unfortunately, to justify their sunk cost, a subset of those individuals tout their knowledge as something by which the rest of us should be impressed. In fact, this comment thread is littered with disdain for peers who dare to tread on their domain with "human-readable names" and "documentation".
In the root article, the author simply suggests that it is more maintainable to use full names for arguments because the code is then self-documenting. It's like using completeVariableNames instead of sht_y1s. Actual comments would suffice, but most code (unfortunately) isn't commented or the comments are done badly.
If a programmer is solo, whatever. Go nuts. Use shortcuts; don't comment. Hard-code paths in your scripts and write 600-line functions. A coder only has herself to blame for the problems she caused.
However, when programming with a group there will always be coworkers that can start being productive sooner (without interrupting you) if things are named and described in plain English and do exactly what it looks like they do.
Script switches are not a remotely interesting problem. Which style you use is a meaningless debate--until you factor in time. Time to debug. Time to look up documentation. Time to memorize. Time is a truly scarce resource, and there exists a better way than rote memorization: making code work in an obvious way. Actively choosing not to employ this idea steals time from others and those of us that lose minutes so a shortcutting programmer can save seconds of typing don't appreciate it.
That said, it's up to one's discretion about what "obvious" means. But nobody should try to argue that making things more readable is inherently bad.
> Unix users should not following the article's advice, they should be embracing Unix's style and ethos; it's part of what's made it such a success.
I always wonder why this is taken so religiously? You're not the first person to write a comment like this, so please don't take it too personally. But is it not possible that the Unix style and ethos is mostly great, but there's a few things here and there that could've been better? You seem to imply that a culture that prefers short options is one of the reasons that Unix became a success. I'm not so sure.
In fact, if `dir /w` had a long version of the option, i would've indeed used it. I think it's a shame that most native Windows commands, unlike their Unix counterparts, don't have long versions of switches. But I doubt that that's contributed much to Windows' success.
And yes, brevity is pretty fundamental to its early culture. Unix was created by mathematicians and scientists that were using it every work day to get stuff down and they recognised and extolled in their writings the power of notation. Imagine maths without superscripts, Σ, etc. So it is with Unix. More wordy notations existed in other OSes at the time, and more noisy commands, e.g. VMS would tell you that "dir/size/owner/prot foo." completed normally, even though that's hopefully the norm. It gets very annoying. :-)
VMS was written later, with a faster interface. Also, you didn't need to specify the entire long option, you only needed to type enough to disambiguate between "/all" and "/almostall" (for instance).
Also, based on the poor advice of this thread's subject, surely one should always write /almostall in one's DCL script for clarity and to lessen the chance of ambiguity as the command evolves? grep's -i is only ever going to mean -i.
VMS died, DCL was often ridiculed, its over-verbose style was a part of that. Its lack of power played a larger part.
sed -n /re/p
is grep. sed's default is to print every line at the end of the script, -n says not to. Larry Wall rightly had perl(1) inherit -n along with perl's -p.(You have to say it in a bad german accent.)
This is not the bread and butter of programming, where everyone worth a damn should be able to decipher "int i = 10;" even if it's not their brand of syntax. There are people who are perfectly capable of understanding and maintaining a piece of software that uses "tr --delete --complement" but would be dumbfounded when confronted with "tr -dc" until they looked it up.
This is, however, the bread and butter of shell programming.
> ... "tr --delete --complement"...
And, likewise, I'm not sure of the meaning of --delete and --complement, but I do understand "tr -dc". I'd have to look up --delete and --complement to work out what they're the equivalent of.
Have you read TAOUP? The entire Unix philosophy hinges around the shell, since the shell is the tool that lets you glue different pieces together. The shell is not outdated.
If you live entirely within one language ecosystem, then you may be tempted to consider the shell an afterthought, and make all services available via API calls instead. But this is inefficient, slows down development, reduces flexibility and limits the capabilities of your programs. This fallacy is old and certainly is not "modern". See TAOUP for details; it explains this far better than I ever could.
This is really old-fashioned thinking. The people who have been in this industry for 10+ years all grew up without computers - and thus had to memorize all of the flags, obscure shell commands, and weird regular expression. What was taught in school back then was to do things perfectly the first time, because CPU cycles were expensive, and bugs were time consuming.
The generation that graduated from college about 2 years ago is the first one that had universal access to a search engine since they knew how to use a computer. This generation (and all future ones for the rest of time) sees memorizing things like this as more of a waste of mental space. What is taught in Universities now is problem solving, research, and larger concepts. There is very little straight memorization, and almost zero programming by hand/whiteboard programming. No current college grad will be able to write a shell script without reference material, but every college grab should be able to write any simple script in less than 5 minutes with Google.
Memorisation isn't the issue. Knowing the tools available and their options is. That comes with study. Unix command line is a boon for problem solving and experimentation, just go and read Jon Bentley's _Programming Pearls_. One can't Google for what one doesn't realise can be done.
I like what you said about "study." There truly is no shortcut for reading documentation available with the system, and assuming by inference what a command is supposed to do based on its options when neither the command nor options are understood just seems to be horribly, horribly bad practice in my mind.
If I am doing code review, then I have the man pages open anyways. If I am trying to write bug-free code myself, then I have the man pages open anyways. In these cases it doesn't much matter what form of flag I use. But the most common case of reading code is a brief scan trying to grok what the code does, which shouldn't require frequent reference to man-pages in much the same way that reading a novel shouldn't require frequent reference to a dictionary.
I understand your concerns about false sense of security and unexpected behavior in corner cases. I've browsed the IOCCC, I've browsed the CVE database, I know how easy it is to hide nasty behavior in unexpected corner case interactions, and that the only defense against them is vigilant attention to documented behavior.
To my mind the most common interactions with code, in decreasing order, are as follows:
1. Executing it. (Flag agnostic, portability issues aside.)
2. Reading it. (Descriptive flags >>> Cryptic flags.)
3. Maintaining it. (Standard flags >> Obscure flags.)
4. Writing it. (Short flags > Verbose flags.)
So I would say the most important thing is that flags are descriptive of their behavior. The second most important thing is that they are common and standardized, but this isn't as important as descriptiveness -- a less common flag that describes its operation better wins. The least important thing is brevity, it only matters once.
You're using it because it comes with the job that's paying you and you want to see what it does and form an opinion on its quality. Much crap code is procured and produced by companies.
“…clarity is often achieved through brevity” — Kernighan and Pike, _The Practice of Programming_. It's an excellent book, I recommend every programmer should have read it. http://amazon.com/exec/obidos/ASIN/020161586X/mqq-20 http://cm.bell-labs.com/cm/cs/tpop/
My opinion remains the same as it was there. If you've already gone through the effort of learning the short options, there is no reason not to continue amortizing that effort by making use of them. On the other hand if you have not really learned the short options, it is only worthwhile doing so if you plan to use them enough in the future that it will pay off.
Of course if you are writing code that you expect to be maintained by someone else, aim it at the fluency that you expect to be able to demand at them. Aiming it lower than that will just make things more painful for you. Aiming it higher will make things more painful for them (and the vast majority of the cost of software development is in maintenance, so they matter more than you do in the long run).
Something else I figured out recently is that if you put the pipe at the end of a line, you don't need a backslash:
echo thing |
grep thingMy own PowerShell scripts often take the form of
Get-Foo |
Where-Object { $_.blah } |
ForEach-Object { ... }
etc., especially with longer pipelines.For something you're planning to deploy to customers, it probably makes sense to play it pretty strict with POSIX.
Likewise, I usually script straight sh for portability if it's going to a customer unless there's a compelling reason to use bash. I'll mix in bash in stuff I write for myself where it makes my life simpler.
"Will I ever have to read and modify this script again? Effectively-100% likely. Will this script ever run anywhere that I don't have the GNU toolchain? Effectively-0% likely."
It's a no-brainer at that point.
If you can't say that second part honestly, reconsider, but a lot of us can.
Not really. A lot of stuff broke when /bin/sh moved to a POSIX-compatibile shell rather than Bash.
#!/bin/bash wilya@home $ /bin/bash
zsh: no such file or directory: /bin/bash
wilya@home $ which bash
/usr/local/bin/bash
(Yes, I'm annoyed when I see #!/bin/bash, especially on scripts which are otherwise basic enough to be portable everywhere) #!/usr/bin/env bash
Assuming env is installed (I believe I had to install a package on OpenBSD to use it) this will find the first instance of bash in the PATH.I really am not worried about that in my world. The dependencies on Linux go a great deal deeper than the GNU toolchain. YMMV.
That's not the case for most people though. I can't even remember the last time I saw even a tiny project assume the world is all "whatever gnu/linux distro I happen to use". Tons of people use linux distros that aren't ubuntu, tons of people use OSX, tons of people use a BSD.
My ultimate rule: write the code that is the most readable, because in 10, 15, 30 years, someone can easily update a script to working arguments from arguments with long words, whereas single letter arguments may have multiple different meanings on different systems. It's the same with naming conventions and code constructs: the how and the what should be obvious from the code.
What current systems have arguments that conflict with those?
Thank you for that. I was aware of the POSIX docs for C/system level programming, but I wasn't sure if command arguments were standardized.
What current systems have arguments that conflict with those?
Ah, but "current" is not always what we get. It's been a while, but I can vaguely remember conflicting single character arguments for basic commands (eg, ls, ps) on OSF/1, SunOS and Linux.
This advice is good not only for others but setting a standard for yourself where you take a moment to learn what exactly is going on.
Don't rock the boat just to adhere to silly style rules. The goal is readability. You're probably already the best judge of what is most readable, so trust your intuition. If you had to look it up, then spell it out. If not, relax and do it the sane way.
Also, [0-9.] not [0-9\.]
I do think it's funny that you said "There isn't and shouldn't be any hard fast rule for this" and then one comment later said my approach is "wrong" :) (EDIT: oops, that wasn't you -- Sorry!)
As for commenting the end of loops - that too just improves readability, especially in long functions. If your editor doesn't show invisible characters, it can be easy to lose track if some indent is part of the 'i' loop or the 'j' loop, for example (yes, that can indicate a bigger problem, but that's not the point. I'm talking about real-world code, not idealistic academic nonsense)
I prefer not to escape dots in char classes, because escapes make it less readable for me. I know this involves a more complex rule, for where one need not escape, but somehow my mind easily treats character classes as a special case region.
No I did not. You're confused as that was someone else. :-)
Do not needlessly escape. Only escape what that flavour of syntax needs you to do. What you may think is a needless escape may actually give different behaviour.
$ sed 's/[x\.]/y/g' <<<'x.\z'
yyyz--David S. Miller
Consider something like this: $ rsync -qaogtHr example.com:/opt/data/ /home/backup/
1. Elaborating all the short flags into long ones will increase readability by explaining this statement but at the cost of more lines of code.
2. All UNIX commands have options to combine short flags. For eg: ls -l -t -r ./ can be written as: ls -ltr ./ This also helps in reducing code. Writing less code helps in managing it more easily.
Long options may help beginners, but once they get comfortable, Short flags may seem more readable!!
Long flags on a command line utility should never change. Short flags may be modified between major versions of a utility, which would break scripts.
Of course this is just a convention, and I'm sure it's not followed 100%. I'll take whatever protection I can get though.
Of course, I can't find any references to back me up on that, so you may very well be correct.
And god forbid you think you know which one it is and end up being wrong... you might not realize until it hits production (scripts not always being the best tested things in the world).
Yes, they might not be supported on BSD.. they're also not supported on Windows, what's your point? It's a lot more likely you'll have to read and/or change the script 6 months down the line when you've forgotten everything about what's in it, then you'll all of a sudden need to run your script on BSD when you've never had to in the past (obviously if portability is a requirement from te beginning, then that changes how you write the script from the start).
Not everything has to be static text, one format does not fit all situations.
I've not written a github robot, though, this is just based on my vague understanding from the robots already out there (whitespace, .gitignore, etc), so please correct me if this isn't actually feasible. :)
Theoretically, I would like to agree that long flags are better than short ones in scripts. In practice, I prefer grep -E. And I can not imagine a tar cvfhz with long flags.