Slashdot Mirror


Beginning Portable Shell Scripting

Joe MacDonald writes "The earliest UNIX shell I encountered was the Bourne shell on a SPARCStation 2 at my university. As with many students of my generation, prior to that nearly all of my exposure to command line interfaces was some variant of DOS. I was quite proficient with the primitive scripting language that was available on such platforms but I immediately felt far out of my depth in this new environment. The commands seemed arcane, possibly dangerous, and almost immediately I regretted stepping into this unfamiliar wilderness without some sort of guide." Read below for the rest of Joe's thoughts. Beginning Portable Shell Scripting: From Novice to Professional author Peter Seebach pages 376 publisher Apress rating 4/5 reviewer Joe MacDonald ISBN 1-4302-1043-5 summary A guide on how to write portable shell scripts.

It was probably a few weeks after that first, rough introduction that I returned for another round with this strange but somehow seductive tool, armed with a book I'd found and a determination to learn it's secrets. I had no idea then that seventeen years later I'd still be learning new tricks, discovering new features and taking so much pleasure from sharing what I've learned with others. In fact, in those early forays into the realm of shells and scripting, I didn't even really have a strong concept of the separation between the shell and the operating system, so at the time I couldn't have conceived of how much fun I would have in later years discussing and debating the relative strengths and weakness of shells with friends and colleagues, but it is probably my favorite touchstone of computer geek conversation. Discussion of shell features, scripting tricks and semantics almost always result in my learning something new and interesting and having a new tool to add to my collection.

Peter's book, Beginning Portable Shell Scripting, therefore may sound like something intended as a gentle introduction, aimed at the initiate — the sort of text I'd been seeking to carry with me when I first attempted to write what I thought of as "batch files" on that now-ancient UNIX machine — but there's more truth in the subtitle, From Novice to Professional, than one might expect. He writes in an accessible, at times conversational, style and presents detailed technical information alongside a mixture of anecdotes and historical detail that does more than simply serve as a technical reference, it helps the reader understand a great deal about why things are the way they are. It was such an entertaining read that I frequently found myself skipping ahead, reading a section I knew was coming up, then resisting the urge to just keep going from that point. The first of these I encountered on page 18 in which he discusses the relative portability of printf in shell scripts. I knew what he knew, it's clearly non-portable and should be avoided, and thoroughly enjoyed the explanation of how he determined his (and by extension my) assumption was in error. Another on page 108 is the sort of good advice all UNIX users, not just those aiming to write good scripts, should take to heart. Many times, though, I've related precisely the same advice to colleagues to be met with confused stares, so it certainly bears repeating.

This book is a desktop reference in the truest sense of the term for me, it is an interesting, at times laugh-out-loud amusing, discussion of how to write shell scripts that will work on the widest possible range of Bourne-derived and POSIXly correct shells and why this is a desirable goal. In true UNIX tradition, the author doesn't provide simply a set of rules, but guidelines that will help you find your own way through the task of creating portable, maintainable shell scripts.

The real meat of the book begins in Chapter 3 (more on Chapter 2 in a moment) with a discussion of control structures and redirection, the latter being perhaps the defining characteristic of UNIX command line interfaces. I struggled somewhat with trying to decide if redirection would be better discussed after the material on how the shell parses tokens, presented in the first part of Chapter 4, but it does seem that the correct logical grouping is the one presented. It would be easy to get lost, for example, in the semantics of why the same streams of redirection tokens behave differently on different shells, but the key concept in the early chapters is that of many tools, each doing a specific task, working in concert. That objective is achieved quite effectively.

Chapters 5 and 6 go into detail (possibly too much for some, just right in my opinion) on how UNIX executes shells and how shells can spawn other shells, the costs and the benefits and the available alternatives for one to make an informed decision. Frequently there isn't one right answer whether some activity is better done in a script, in a shell function or in a subshell, but the material here will certainly aid in making those determinations. My personal bias being almost always toward writing a shell function — perhaps an indication I've had too much exposure to C programming, perhaps more due to a frugal upbringing and my own sense that spawning a whole new shell to do something is overkill — had me wishing for a larger section on the value of such constructs, but there should be enough there for me to win some converts to my cause.

By far the sections I learned the most from, however, would be Chapter 7: Shell Language Portability and Chapter 8: Utility Portability since I actively avoid exposure to other shells. I have my two preferred options and a third that I will use when presented with no alternative. While this does mean I know "my own" shells very well, it also means that I often bump into the furniture, so to speak, when I find myself using a new shell. These chapters haven't been immediately useful to me, but I know they're the ones that I'll be turning to in the future, I've needed something like them in the not-too-distant past, after all.

The final three chapters assemble the information presented in the earlier sections and suggest a sort of "best practices" approach to writing scripts. Concepts like "degrade gracefully" seem like pretty fundamental ideas when you hear them but I frequently find myself writing functions or scripts that don't do that at all when intended for a limited, usually singular, audience. It may seem like an okay idea when you're doing something for your own use, but when you write a complex function that works then discover a bug in it two or three years late and you have to return to fix it, it can be just as helpful for it to simply fail in an informative way as it would be to have detailed comments explaining the intent and the mechanics.

Truly, there's something here for everyone. In my office I'm considered something of an expert when it comes to complex regular expressions and the subtleties of using them in different editors and tools, but Chapter 2 and Appendix C both had enough new material in them that I found myself frequently making notes in the margins.

I have many, many books in my bookshelf in my office but nearly none on my desk. Beginning Portable Shell Scripting is going to be one of the very few that will be spending a great deal of time lying flat on my desk, in easy arm-reach.

You can purchase Beginning Portable Shell Scripting from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

186 comments

  1. portable shell scripting is an oxymoron by rlseaman · · Score: 1, Flamebait

    Even if a shell script is portable, the underlying OS will always fail to be for any task significantly complex to do useful work.

    1. Re:portable shell scripting is an oxymoron by MrEricSir · · Score: 1

      Who needs to invoke the OS when you can calculate Pi with only a mere batch script?
      http://thedailywtf.com/Comments/Stupid-Coding-Tricks-A-Batch-of-Pi.aspx

      --
      There's no -1 for "I don't get it."
    2. Re:portable shell scripting is an oxymoron by jellomizer · · Score: 2

      Care to elaborate?

      I have seen some rather complex scripts that are portable that do some useful things.

      --
      If something is so important that you feel the need to post it on the internet... It probably isn't that important.
    3. Re:portable shell scripting is an oxymoron by MrEricSir · · Score: 1

      That link should really be
      http://thedailywtf.com/Articles/Stupid-Coding-Tricks-A-Batch-of-Pi.aspx

      (I should write a shell script to correct my comments.)

      --
      There's no -1 for "I don't get it."
    4. Re:portable shell scripting is an oxymoron by myVarNamesAreTooLon · · Score: 5, Funny

      (I should write a shell script to correct my comments.)

      You're in luck! I have recently heard of a book that could help with your scripting...

    5. Re:portable shell scripting is an oxymoron by code4fun · · Score: 1

      Check out GNU autoconf. That's a good example of how a script works on *nix box. And, yes, they are useful!

    6. Re:portable shell scripting is an oxymoron by rlseaman · · Score: 3, Interesting

      As usual, it comes down to use cases. Describe the useful things that are done. One might choose to write a shell script to perform some pure mathematical utility function, but this certainly isn't the usual role of such scripts. Rather, one uses a shell script when accessing files (logs, etc.) on the disk, or when opening sockets, or when spawning host level commands. Other device level access is often required, for instance, a local or UTC clock might be consulted, requiring knowledge of timezones. All of these are very dependent on whether the script is running under a BSD or Sys-V flavored OS (assuming Unix, of course), or even on micro-versioning of specific OSes.

      The question of complexity is also not some challenge to find a lengthy script, but rather a statement of the inherent design-level complexity of the application.

    7. Re:portable shell scripting is an oxymoron by Fred_A · · Score: 2, Funny

      That link should really be
      http://thedailywtf.com/Articles/Stupid-Coding-Tricks-A-Batch-of-Pi.aspx

      (I should write a shell script to correct my comments.)

      Bash script, ASPX page, culture clash.

      --

      May contain traces of nut.
      Made from the freshest electrons.
    8. Re:portable shell scripting is an oxymoron by dgatwood · · Score: 5, Interesting

      Well, there is some truth to the GPP's comment. Linux and Mac OS X don't even agree on how to tell echo not to print a newline or how to enable extended regular expression mode in sed. May heaven help you if you want to do something as esoteric as creating or mounting a filesystem, creating or mounting a disk image/ramdisk, talk to a USB device in any way, get a list of processes in any useful way, etc. There's a very big lack of standardization in a lot of things you might like to do with scripts, in other words. The Single UNIX Spec and POSIX are not quite sufficient, but more annoyingly, most OSes (Linux, *BSD) out there don't even come close to conforming to it, so you end up with this dichotomy between BSD behavior and AT&T behavior.

      That said, a lot of things are standardized, and many others can be worked around with clever use of variables (or possibly eval in a few extreme cases). I've written chapters on the subject myself. The big things you need to remember are that $(( $FOO + 3 )) is not portable, nor for ((...)), nor >&, nor anything involving extended regexp except using Perl, that even "the one true awk" is not quite SUS-compliant, GNU awk doubly so, bash triply so, that you should use printf instead of echo for output if you don't want newlines, that signal numbers are not portable (for trap), that proper quoting of arguments is crucial, and that you need to work with the bare minimum base behavior of utilities (using few or no flags) if you expect any hope of portability without needing to make platform-specific changes.

      For some quick examples of some interesting portability issues, read some of my comments in the games at shellscriptgames.com or search for the word "compatibility" in Apple's "Shell Scripting Primer". It's a real eye opener to see how many portability problems exist even for fairly simple shell scripts.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    9. Re:portable shell scripting is an oxymoron by Fred_A · · Score: 3, Informative

      As usual, it comes down to use cases. Describe the useful things that are done.

      Take a naked box and boot it (/etc/init.d/*) ?
      I know it's a bit trivial but it still qualifies as useful in my book.

      Actually /etc is just pretty much a collection a collection of fairly useful shell scripts. I've always found it interesting that Unix was mostly held together by /bin/sh (aka /bin/bash on a lot of systems nowadays) and spit. And that it worked.

      To take one of the posts above where the poster had been exposed to DOS. The DOS system (although it wasn't really a system, merely a program loader) was configured by the autoexec script. All the Unix do the same with a number of chained scripts (and their order can even dynamically change nowadays) all running sh (or an extended version of it).

      I still wonder at it sometimes. It's simple and accessible on one side. And it can degenerate into an awful mess on the other :) (less so nowadays thankfully)

      More ?

      Anyway, wanted something useful the shell could do ? How about run the whole operating system (find a service that isn't actually handled by a !#/bin/sh script...).

      --

      May contain traces of nut.
      Made from the freshest electrons.
    10. Re:portable shell scripting is an oxymoron by rlseaman · · Score: 1

      Booting a computer is almost the definition of non-portable. Not sure what you mean by a naked box, but there are all the device drivers to load, clocks to set, file systems to mount, services to start. These are precisely the things that vary from one flavor of Unix (or Linux) to another. The script itself may be very portable, but the underlying description of the resources - or even the description of this description - will not be portable

      I'm a bit at a loss for why my message has been labeled flamebait :-) These assertions seem unremarkable. Personally, I'm all for writing portable code, whether in an interpreted or compiled context. But the real challenge to portability lies in the libraries you call (the OS itself for shell scripts), not in the language you write the code in.

    11. Re:portable shell scripting is an oxymoron by ultrabot · · Score: 2, Informative

      Check out GNU autoconf. That's a good example of how a script works on *nix box. And, yes, they are useful!

      Autoconf is also a horrible peace of crap. One of the better reason to hate the concept of shell scripts, actually.

      Check out SCons for comparison:

      Program('hello.c')

      or

      SharedLibrary('foo', ['f1.c', 'f2.c', 'f3.c'])

      And that's pretty much it. I'm not sure all the horrors required by autoconf would fit into a slashdot posting.

      --
      Save your wrists today - switch to Dvorak
    12. Re:portable shell scripting is an oxymoron by Anonymous Coward · · Score: 0

      Hmm... did someone re-invent imake?

    13. Re:portable shell scripting is an oxymoron by ultrabot · · Score: 1

      Hmm... did someone re-invent imake?

      No, SCons does not generate makefiles.

      SCons here was just an example to illustrate how much Automake sucks. Obviously we have other systems like CMake as well.

      --
      Save your wrists today - switch to Dvorak
    14. Re:portable shell scripting is an oxymoron by steelfood · · Score: 1

      From my experience, shell scripts that use a significant amount of non-shell builtin commands are not portable. The typical shell script is highly dependent on the awk, grep, sed, etc. version on the system. And that varies not only between platforms, but between OS versions.

      Simple things, like the improved mv that's floating around, tend to be easier to port. But the chance of a successful port is inversely proportional to the complexity of the script. As well, usefulness, while a loaded term, tends to be proportional to simplicity.

      Your experience might be with long scripts (not to be mistaken with complex scripts) that predominantly make use of shell builtins to do all of the work, or with a relatively homogenous network environment. But your situation if true, from my experience, is rather unique.

      --
      "If a nation expects to be ignorant and free in a state of civilization, it expects what never was and never will be."
    15. Re:portable shell scripting is an oxymoron by dgatwood · · Score: 1

      I'm not sure all the horrors required by autoconf would fit into a slashdot posting.

      I think it could fill an entire book.

      • Start with all the custom extensions for things like GNOME and KDE that each have their own custom syntax instead of coming up with a single syntax that works reliably, and many of the modules aren't included universally with various OSes and/or distros, so trying to rebuild the "configure" script with autoconf results in utter failure unless you have all the various development packages installed, including pieces that are optional.
      • Next, add the fact that about half the Autoconf modules I've seen don't respect shell variables like $CFLAGS and $LDFLAGS, so you end up with a dozen different --with-foo-lib directives that are specific to each individual project to force it to look in the right place if it isn't where the original Autoconf script author expected it (and even then, sometimes I end up having to hack the Autoconf script and manually splice in extra arguments in the compile directive to make it work).
      • If you ever need to compile with a different compiler, you're in an even bigger world of hurt, since most AC modules don't seem to care about the value of $CC.
      • Oh, yes, and if you need to pass linker flags, you'll often have a great deal of fun if those flags aren't supported natively by gcc.

      And so on. Anybody who has ever used Autoconf at any significant level could probably go on for weeks....

      Autoconf is the antithesis of portability except when porting to platforms to which the software has already been ported, and then really, what's the point? So you save a couple of extra tiny makefiles, but you end up with something that's an utter bear to port to any platform instead of having a makefile for BSD that you can tweak trivially and port to a similar platform. When I'm porting something to a new platform, I'd much rather get a Makefile with neatly laid out variables at the top for things like FOOLIBDIR, BARLIBDIR, etc. and modify it by hand than get an Autoconf script (no matter how well written) any day of the week.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    16. Re:portable shell scripting is an oxymoron by seebs · · Score: 3, Informative

      Portability isn't boolean.

      I wrote a wrapper around cdrecord to clean up the UI, automatically handle things like creating an isofs from directories, and so on.

      It's not 100% portable; every new system, I change the path to cdrecord, the device spec for the CD drive, and the command used to eject a CD.

      Everything ELSE stays the same, and I don't need to remember how to use mkisofs, or anything like it. Directories, bzipped images, whatever; it gets burned correctly. I win.

      If the script were not written in otherwise-portable shell, it might not work on the broad variety of boxes I've wanted to use it on.

      I've done scripts to handle tasks like "open this file" (not as flexible or smart as the OS X one, but quite good about various compressed tarballs and archives). Surprisingly portable.

      I have a script for the idiom of "for every file named or provided as standard input, run it through this filter in place". Repeating commands at intervals, for a given number of times, until they fail... Tons of little utilities like this that save me time.

      If you want complete applications with no dependencies, that's harder to find. That said... Have you ever used autoconf to configure something? That's a fair bit of portable shell right there...

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    17. Re:portable shell scripting is an oxymoron by rlseaman · · Score: 1

      I had to laugh. I wrote a similar wrapper script for cdrecord. This may say more about mkisofs and the management of recordable media than it does about scripting :-)

      This script (well, I broke it into the obvious separate steps of building the ISO image and dumping it to duplicate media) was orchestrated from within a Unix daemon called as a BSD lpd filter. Whatever else it does, lpd serves as a reasonable queuing manager. A humorous but pragmatic choice.

      That was an evolution of a system for archiving digital imaging data onto exabyte tapes. The original tape-based system was ported after a few years from SunOS to Solaris, that is, from BSD lpd to Sys-V lpsched. I balked at repeating the port for optical media, very much due to portability issues unrelated to scripting. Scripting is the least of your worries with portability.

      The digital archive has long since evolved to a system with a replicated online (hard drive based, that is) architecture. Much more portable (non-boolean, as you say), but certainly not 100%

    18. Re:portable shell scripting is an oxymoron by lilo_booter · · Score: 1

      Sorry, but no, that is nowhere near 'pretty much it' - as soon as you want to link in with libraries in a cross platform manner, generate platform specific release mechanisms (thing mac framework and app bundles), or do anything which doesn't fall into your example there, you're back in wild and woolly territory... and yes, those things are beyond autotools, but they're also beyond the core scons too.

    19. Re:portable shell scripting is an oxymoron by seebs · · Score: 2, Insightful

      Yes, you're quite right that this says a lot about poor user interface choices in some utilities.

      Thinking about it more: One of the key applications of portability involves scripts which are never ported.

      It's that I don't use only one machine. I use a Mac desktop, a BSD server, and some Linux servers. Even if I'm just typing "for i in..." on the command line, I don't want to try to remember three or four different sets of commands to work across these environments. I want to write things that work the same everywhere -- not just so I can run them multiple places, but so it doesn't matter which machine I'm on when I'm typing.

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    20. Re:portable shell scripting is an oxymoron by Tacvek · · Score: 1

      Most of those issues are primarily issues with third party autoconf m4 modules, or with people who don't know what they are doing adding functionality to configure.ac. That is not really autoconf's fault. (The fact that it is easy to mess things up if you don't know what you are doing might be autoconf's fault). And proper use of autoconf can and does make portability easier, although I will admit little outside the GNU project uses autoconf properly, and there are even exceptions within the GNU project.

      The worse issue is that many of the automake m4 scripts were buggy, running dozens of tests not useful to the package in question. (One of many examples: I often see configure scripts checking if I have a fortran compiler, despite being simple C packages.)

      --
      Stylish sheet to fix many problems in Slashdot's D3: https://gist.github.com/801524
    21. Re:portable shell scripting is an oxymoron by seebs · · Score: 1

      You miss the point.

      Autoconf is godawful crap, no doubt about it. But people still use it. You know why?

      *IT WORKS*. It works on Linux. It works on Solaris. It works on BSD. It works on Tru64. It works on Cygwin. It works all over the place. A decently written autoconf script works for cross-compiling. It doesn't require a particular language to be installed.

      I've used SCons-based projects. It was a nuisance to get it set up and working. Sure, it does some stuff nicely -- but I couldn't just grab it and use it on any possible target. (As I pointed out in my article about Second Life, this is an example of a good tradeoff for an internal tool...)

      Engineering isn't always about picking the prettiest thing; it's sometimes about making tradeoffs, and figuring out what works in the environments under consideration...

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    22. Re:portable shell scripting is an oxymoron by Tetsujin · · Score: 1

      Care to elaborate?

      I have seen some rather complex scripts that are portable that do some useful things.

      Here's one: most uses of "find" together with "xargs"...

      By default, "find" prints out newline-delimited filenames, while "xargs" consumes whitespace delimited values... So if you've got filenames with spaces in them, you're in trouble.

      The GNU solution is the "--print0" argument to "find", and the "-0" argument to "xargs" - which uses the zero-byte as a delimiter for both commands... The problem is, this isn't supported in other implementations of "find".

      This is just one example of a command where the command-line switches, or input or output form of a command may vary drastically between different platforms. MacOS is a prominent example of an environment where common GNU command-line switches aren't supported...

      The problem is further complicated by the fact that there's no good mechanism provided by the shell to deal with these issues. There's no way to say "I want to run find, but specifically I need GNU find" - and GNU find on your system could be "find", "gfind", or it could just not be there at all.

      You can get far by sticking to the lowest-common-denominator set of features... but I think the shell is seriously limited in terms of providing a stable set of features across platforms - the set of commands can vary wildly across distributions or OSes, and the shell itself doesn't provide any means to deal with that problem. I'd really like to find a good solution to that...

      --
      Bow-ties are cool.
    23. Re:portable shell scripting is an oxymoron by WarJolt · · Score: 1

      'sed', 'perl', 'awk' and 'mount' are not part of the shell.
      for and trap are part of a posix standard shell.

      It's subtle, but the differences are easy to understand. The best example I can think of is most linux systems I've used use bash, but Ubuntu make /bin/sh a symbolic link to /bin/dash because it's faster. Many scripts are broken because they expect /bin/sh to be a symbolic link to /bin/bash. This is not an assumption you can make.

      This causes a problem for example when you use bash functions like popd which isn't part of the posix standard. If you want to use popd use the right shell by adding #!/bin/bash to the top of your script.

      awk and perl should behave the same even if you change shells.

    24. Re:portable shell scripting is an oxymoron by chthonicdaemon · · Score: 1

      I have noticed an alarming trend in build tools -- they assume that you are using basically one language for your whole project. One of the reasons Make and co have so much more to specify is that they work for a much wider range of application. I looked into CMake just long enough to see that it would not work to make something that's written in five or six languages.

      It's obvious that you can buy simplicity by special casing. What's hard is keeping a bit of it when you generalize. I had the same experience lately with testing frameworks, and I came to realise why dejagnu is cool and is still used even when there are much more polished frameworks available for specific workflows.

      --
      Languages aren't inherently fast -- implementations are efficient
    25. Re:portable shell scripting is an oxymoron by dgatwood · · Score: 1

      Fair enough about those things being extensions, though many are supported so broadly (the $(()) math syntax, for example) that it surprises people when they don't work. Unless you code on the Almquist or Debian Almquist shell regularly, chances are very good that you'll be in for a rude awakening if you ever switch to it. Things that nearly every /bin/sh implementation on the planet has provided for a decade or more (not just bash) simply don't work in ash or dash because they depend on behavior that isn't explicitly specified in the POSIX spec. That makes operating systems that use those shells great test platforms for testing scripts, albeit painful platforms for actual end users. :-)

      That said, I would disagree with your criticism that awk, sed, etc. are not part of the shell and are thus not relevant to a discussion of script portability. If you want to talk only about pure shell scripts that don't actually run any programs, then yeah, they're pretty close to perfectly portable as long as you avoid a handful of gotchas, and they are pretty close to useless, too. In any reasonable discussion of shell scripting, you can't realistically limit discussion to talking about the language itself. You can't do much without exceeding the bounds of shell control statements and shell builtins (which, BTW, vary from shell to shell as well even within the Bourne-compatible camp). Okay, so maybe awk is a little too obscure, but that's just the tip of the iceberg.

      Beyond really trivial scripts, most scripts that actually do something useful are likely to have to call, at minimum, sed, grep, echo, and expr; a sizable percentage will also use tr, bc, head or tail. With the possible exception of bc, everything on that list, IIRC, has at least one significant flag difference among Linux, the *BSDs, and Mac OS X, not even counting differences on AIX, Solaris, or any of the other myriad UNIX systems. That's why people find portable shell scripting so difficult; they end up accidentally using some flag or feature that is Linux-specific, BSD-specific, Mac OS X-specific, etc. without knowing they are doing so because the documentation doesn't mention that the flags are not part of the POSIX spec.

      The POSIX specification is a good place to start when writing shell scripts that you expect to work correctly on other platforms. If you design to that, you'll only have a handful of compatibility problems (such as the echo -n blah vs. echo 'blah\c' problem).

      As for your assertion that tools like awk should stay the same if you change shells, that is only partially true. There are parts of Mac OS X that automatically define magic shell variables (documented in the man pages for the various tools) that turn on or off support for legacy BSD syntax support. This allows POSIX compliance for passing the compliance tests and for general shell scripts while maintaining backwards compatibility for certain critical scripts like parts of startup items, installer preflight and postflight scripts, and so on. So even a given utility on a given OS can't be guaranteed to work the same way in every environment. That's why it is important to pay attention to these sorts of details when writing shell scripts. :-)

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    26. Re:portable shell scripting is an oxymoron by mzs · · Score: 1

      Good ones, but you forgot the biggie that I see people get tripped-up on the most, test.

      Sometimes test -a mean test -e and sometimes it is meant to be used [ exp1 -a exp2 ]. Most often these days the confusion is on solaris using ucb.

      So the moral is, never use -a, -o, or -e in tests.

      (Yes there were ancient versions of test that did not have AND and OR, so you use && and || from the shell instead.)

    27. Re:portable shell scripting is an oxymoron by Anonymous Coward · · Score: 0

      So if you've got filenames with spaces in them, you're in trouble.

      Set the built-in IFS variable to be a newline.

    28. Re:portable shell scripting is an oxymoron by xouumalperxe · · Score: 1

      Well, an init.d script is the farthest you can get from portable while still being a pure script. On the other hand, a script made of sh, sort, awk, sed, grep, and a few more similar tools will be quite portable. If you make sure you keep to the standard behaviour of all those tools (as opposed to using gawk-specific features, for example), it'll be even more portable. Etc etc. When you talk about writing shell scripts, you're usually not talking about pure sh, you're talking about glue code around the basic unix toolchain -- and that's typically the only limit to portability.

    29. Re:portable shell scripting is an oxymoron by Jurily · · Score: 1

      You can get far by sticking to the lowest-common-denominator set of features... but I think the shell is seriously limited in terms of providing a stable set of features across platforms - the set of commands can vary wildly across distributions or OSes, and the shell itself doesn't provide any means to deal with that problem. I'd really like to find a good solution to that...

      Python. Shell was never meant to be portable.

    30. Re:portable shell scripting is an oxymoron by Tetsujin · · Score: 1

      You can get far by sticking to the lowest-common-denominator set of features... but I think the shell is seriously limited in terms of providing a stable set of features across platforms - the set of commands can vary wildly across distributions or OSes, and the shell itself doesn't provide any means to deal with that problem. I'd really like to find a good solution to that...

      Python. Shell was never meant to be portable.

      Right. But then it's not exactly shell programming any more, is it? Rather than solving the problem, we've avoided it. (Which is fine when all you want is to write a portable script - but not so great when what you want is to improve the shell.)

      To put it another way, why shouldn't we expect the same level of portability (and functionality!) from the shell as we see from a language like python? Why shouldn't the shell provide facilities that are every bit as good as those you'd find in a scripting language like Python, Perl, or Ruby, with their large collections of well-implemented (and more-or-less stable between revisions) libraries?

      A particular shell program (or Python library) is either present, or not... A particular version of a particular program or library is either present, or not. Why shouldn't the shell have the same ability to handle those cases intelligently that Python would?

      --
      Bow-ties are cool.
    31. Re:portable shell scripting is an oxymoron by Tetsujin · · Score: 1

      So if you've got filenames with spaces in them, you're in trouble.

      Set the built-in IFS variable to be a newline.

      xargs doesn't use $IFS. And a shell "foreach", in bash, anyway, would wait for the whole result of "find" to be available before starting the loop - buffering the whole result instead of stream-processing it.

      --
      Bow-ties are cool.
  2. more than this? by tritonman · · Score: 3, Interesting
    1. Re:more than this? by seebs · · Score: 2, Insightful

      Yes. ... Well, come on, what do you expect me to say?

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
  3. Bah, dangerous? by sepelester · · Score: 1

    I was behind the comfortable wall of a multi user system even with disk quotas. We had access (read only) to our backups and pretty much coudn't screw up. Bourne was standard but I used zsh and later switched to bash. Man pages was all we had to study and we competed in learning as much as possible, writing cool scripts, exploiting the system in various ways. The system was rooted and sabotaged a couple of times but nothing in it was critical in any way. A playground really. I remember the tingling feeling of the 'su' command, the only really dangerous one. Nice that they write books about this but nothing beats the good old feeling of having worked HARD to get the knowledge. The cry of success is so much louder.

  4. If you have a choice... by ultrabot · · Score: 4, Insightful

    Don't do it.

    Shell scripts have horrible error handling, and quickly become a maintenance nightmare. These days, e.g. Python is installed everywhere you need to go.

    Just do this:

    def c(s): os.system(c)

    and you have mostly covered the area where shell scripts excel. You can still write minimal "shell scripts" inside c().

    Unluckily, you still *need* to grok shell scripting to some extent, or at least be able to read them. Just don't write them if you can help it.

    --
    Save your wrists today - switch to Dvorak
    1. Re:If you have a choice... by ncw · · Score: 4, Insightful

      I agree!

      My personal limit is 10 lines for a shell script. If is longer than that I convert it to Python.

      Python scripts have the advantage that they work on Windows too, and they have lots of os independent abstractions for file names, processes etc.

      Why learn an arcane language like sh when you can learn a nice well structured language like Python and write better scripts?

      A few years ago I would have used Perl rather than Python, but I'm converted now ;-)

      --
      Every man for himself, all in favour say "I"
    2. Re:If you have a choice... by Anonymous Coward · · Score: 0

      You mean: def c(s): os.system(s)

    3. Re:If you have a choice... by Nasarius · · Score: 1

      Or better, just...

      c = os.system

      --
      LOAD "SIG",8,1
    4. Re:If you have a choice... by $RANDOMLUSER · · Score: 3, Insightful

      Shell scripts have horrible error handling, and quickly become a maintenance nightmare. These days, e.g. Python is installed everywhere you need to go.

      That's exactly what the Perl people said years ago, and we all know how well that worked out (for low maintenance sysadmin-type tasks). I know the sinking feeling I get every time I find a crontab entry pointing to a Perl script.

      --
      No folly is more costly than the folly of intolerant idealism. - Winston Churchill
    5. Re:If you have a choice... by Etherized · · Score: 2, Interesting

      I can't agree more. I switched over to python for all non-trivial scripting a couple of years ago, and I find it much more pleasant. I even sometimes use iPython instead of bash when I know I'll need to do something complex interactively.

      By the way - if you like using python to control systems, you might also enjoy the func project.

    6. Re:If you have a choice... by ultrabot · · Score: 1

      Or better, just...

      c = os.system

      Ok, I cheated. I usually have it like this:

      def c(s):
          print ">",s
          os.system(s)

      --
      Save your wrists today - switch to Dvorak
    7. Re:If you have a choice... by JamesP · · Score: 1

      To me it's mixed feelings there

      Even though python is very easy, you can't beat the ease of use of find / sed / others

      And in python you would need to go to popen/pclose usually, to get the output and return values

      --
      how long until /. fixes commenting on Chrome?
    8. Re:If you have a choice... by digitalhermit · · Score: 4, Informative

      Python is nice, but hardly installed everywhere. It's available on Linux certainly, but not always on AIX or Solaris. Yes, it is just an installation away, but many of the systems I maintain require change management procedures to even chmod a file.

      Shell scripts do have decent error handling for what they need to do. With traps and proper usage of error codes, they are not much different from lower level languages.

      I'd agree that I now *prefer* to write longer scripts in Python. However, few of the people I work with know Python, or even Perl. They can get around with korn and bourne as these are the default scripting languages on more traditional Unix systems.

      Which comes down to the gist of the issue. Do you write code in a language you prefer or one that can be maintained by the admins? I'd argue that it doesn't matter what language you use. If you write poor code in shell you will likely write poor code in Python too.

    9. Re:If you have a choice... by bol · · Score: 1

      While I completely agree that Python is a fantastic system admin tool and a very suitable replacement for almost all shell scripting I disagree that shell scripts have to have horrible error handling.

      "if [ $? != 0 ]; then" goes a long way and you get bonus points for wrapping it in a function.

      There are some tasks that belong in a shell script and some that belong in a programing language like Python. It's all about the right tool for the job.

    10. Re:If you have a choice... by cmdr_tofu · · Score: 2, Insightful

      The tradeoff is that your scripts have a huge memory footprint now. I loathe shell script as much as the next person, but find it necessary when I am working in a minimal busybox-type environment. Perl/Ruby it is whenever I have the chance.

    11. Re:If you have a choice... by swillden · · Score: 1

      Shell scripts have horrible error handling, and quickly become a maintenance nightmare. These days, e.g. Python is installed everywhere you need to go.

      That's exactly what the Perl people said years ago, and we all know how well that worked out (for low maintenance sysadmin-type tasks). I know the sinking feeling I get every time I find a crontab entry pointing to a Perl script.

      There is a big difference between Perl and Python. While you can write readable Perl, or write horribly opaque Python, there's a reason that Perl has a reputation as a write-only language and Python has a reputation for being quite readable.

      Then there's the guy I worked with years ago who wrote (writes, I'm sure) all of his scripts in elisp...

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    12. Re:If you have a choice... by ultrabot · · Score: 1

      "if [ $? != 0 ]; then" goes a long way and you get bonus points for wrapping it in a function.

      What I like about the python way is that you don't have to write any of that - if something fails, the whole function fails (unless you specifically catch the exception). No need for explicit error handling to clutter your scripts.

      --
      Save your wrists today - switch to Dvorak
    13. Re:If you have a choice... by Tikkun · · Score: 2, Insightful

      Why learn an arcane language like sh when you can learn a nice well structured language like Python and write better scripts?

      Where I work pretty much everything has bash already (I install cygwin on all the Windows boxes. Of course, Python is usually there too :) ).
      If you already have a bash script (or find one via the Google), changing it is usually simpler than porting it to Python.
      If you work with people that already know bash scripting but don't know Python using the lowest common denominator can be easier than training.
      There is less memory overhead for a simple shell script than there is for a simple Python script.

      This being said, I try to keep my bash scripts under 40 lines and port them to python if they get more complex and I know the machine I'm going to be using them on has Python.

    14. Re:If you have a choice... by Anonymous Coward · · Score: 0

      Shell scripting is fun

      If you don't know how to write error handling yourself, then your not much of a coder. No matter what language... Its called, write the code. Test the code... Check the values of your returns and variables. And then modify your code.

      Seriously, I have never had issues with error handling... And I've writting log parsing routines in nothing but Shell scripts.

    15. Re:If you have a choice... by Haeleth · · Score: 2, Interesting

      These days, e.g. Python is installed everywhere you need to go.

      No it isn't. Not even remotely close.

      And in most cases the response to a request to install an entire programming language would be flat rejection, turning to raucous laughter when they realise you only want it because you don't like any of the several scripting environments that are already available.

    16. Re:If you have a choice... by fjollberg · · Score: 2, Informative

      > These days, e.g. Python is installed everywhere you need to go.

      Sorry, but no, it isn't.

    17. Re:If you have a choice... by ultrabot · · Score: 1

      These days, e.g. Python is installed everywhere you need to go.

      No it isn't. Not even remotely close.

      And in most cases the response to a request to install an entire programming language would be flat rejection, turning to raucous laughter when they realise you only want it because you don't like any of the several scripting environments that are already available.

      Sounds like a rather dysfunctional working environment.

      I had something like this in mind when I said "everywhere you need to go" (as opposed to just saying "everywhere").

      --
      Save your wrists today - switch to Dvorak
    18. Re:If you have a choice... by Anonymous Coward · · Score: 1, Interesting

      Why learn an arcane language like sh

      Because sometimes it is exactly the right tool for the job. There are many tasks for which python or perl are overkill. Specifically, things which could be accomplished interactively on the command line (like repetitive tasks) but are better automated. Writing shell scripts also makes you more proficient on the command line, which is a valuable skill for any programmer or sysadmin. Your knowledge of command line tools and where/when to use them will surely increase.


      #!/bin/sh

      cat musicbrainz.xml | sed 's/>/>\n/g' | grep 'title>$' | sed 's/musicbrainz.txt

      This is a quick and dirty script I use to convert a musicbrainz XML file (found on the details page of each album) to straight text. It's part of a collection of scripts which make up my custom tagging and music management system. It works great. But imagine what the equivalent script would look like in python or perl. A lot longer, for starters.

    19. Re:If you have a choice... by Lord+Ender · · Score: 3, Insightful

      That's not what they said years ago. People arguing to use Perl instead of Bash did so because Perl was just far more functional. Perl and Bash both have pretty terrible maintainability, but Perl is a million times more functional.

      Python and Ruby have the functionality of Perl without the maintenance issues inherent in a language which is really a hodge-podge of ancient unix idioms.

      --
      A slashdotter who didn't build his own computer is like a Jedi who didn't build his own lightsaber.
    20. Re:If you have a choice... by 0xABADC0DA · · Score: 3, Informative

      Shell scripts have horrible error handling, and quickly become a maintenance nightmare. These days, e.g. Python is installed everywhere you need to go.

      Python doesn't help much over shell scripts without extra libraries, which may or may not be present on any given system.

      Python has changed incompatibly several times already.

      Python has a large startup overhead:
          20 seconds: 1000x python -c 'print("test")'
          2 seconds: 1000x sh -c 'echo test'

      Python is clumsy to use for gluing several programs together.

      Python is not the same syntax as the shell. If you don't learn the shell then your day-to-day command lines are gimped.

      So Ruby or Python or anything else is better for writing actual programs that do anything complicated, but there are plenty of appropriate uses for shell scripting. Ruby is actually much better... since it has a sensible syntax you could make a rubysh that wouldn't suck.

    21. Re:If you have a choice... by Anonymous Coward · · Score: 0

      Sorry, that should be:

      cat musicbrainz.xml | sed 's/>/>\n/g' | \
      grep 'title>$' | sed 's/</\n</g' | \
      grep -v '^<' | grep -v '^$' | sed '1d' >musicbrainz.txt

    22. Re:If you have a choice... by medoc · · Score: 2, Interesting

      One reason may be that Python's startup time is an order of magnitude slower that a shell's, and sometimes it does matter, even for scripts of much more than 10 lines.

    23. Re:If you have a choice... by nevermore94 · · Score: 4, Interesting

      Lol, under 40 lines... Where I have worked for 10 years, we use portable shell scripts to maintain hundreds of database servers on several different UNIX platforms including Linux, AIX, DEC, and even SCO. Our older utility suite which had a full character curses like menu system is comprised of around 54,000 line of shell including comments in 214 scripts. Our new system which has a full web interface is around 64,000 lines of shell including comments in 226 scripts, plus it makes calls out of the older utilities as well. The longest individual script I maintain is currently 2,741 lines long, but it includes many functions from our shell libraries and makes calls out to even more shell utilities. And, it all still works on all of our Linux, AIX, DEC, and SCO servers. Also, as being a Java programmer, I would hate to even try to calculate how many lines of code it would take to try to duplicate all of the functionality in Java.

      --
      Nevermore.
    24. Re:If you have a choice... by alexborges · · Score: 2, Funny

      I dont necesarily disagree with what you say here.

      Ill just point out that your carpet is UGLY AS HELL.

      And I Bash Script quite a lot (and even have fun at that).

      --
      NO SIG
    25. Re:If you have a choice... by harry666t · · Score: 1

      try this...

      from commands import getoutput as cmd
      foo = cmd("echo bar")

      I often find myself writing small, special-purpose wrappers for some commands, like ps or find. I liked the MS PowerShell's concept of piping objects instead of text. Imagine... "ps | grep name=spam | kill". Yeah, sh sucks.

    26. Re:If you have a choice... by andr386 · · Score: 1

      Does python can really replace shell scripting ? I'd really like to know. When I write scripts, I use intensively pipes and awk. Would python allow me to do the same kind of things that awk do ?

    27. Re:If you have a choice... by oliderid · · Score: 1

      I know the sinking feeling I get every time I find a crontab entry pointing to a Perl script.

      For the younger folks out there, the feeling is similar too:
      mono /script/all_your_code_belong_to_us.exe

    28. Re:If you have a choice... by Anonymous Coward · · Score: 0

      As a note 'set -e' will make bash terminate when a non-zero error code is returned.

    29. Re:If you have a choice... by seebs · · Score: 0

      And then the whole script goes wildly crazy because it ends up in an unanticipated state? Sounds delicious.

      There's times to abort in the face of error... and times not to.

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    30. Re:If you have a choice... by dfn_deux · · Score: 4, Insightful

      maintenance issues inherent in a language which is really a hodge-podge of ancient unix idioms.

      What a ridiculous claim, there are no "maintenance issues" with ancient idioms... The very fact that those techniques are ancient shows how incredibly flexible and useful they are. I'd much rather use conventions which are widely accepted and in many cases are required by Posix/SUS/XPG4 than find myself having to hack up my stuff to accommodate broad and pervasive changes such those experienced when moving from python 2.x to python 3.x...

      People who are constantly advocating against shell scripts tend to be those who see system administration as something it isn't; namely a low level development job. When in reality a sys admin uses shell scripts to glue together existing products of developers in order to manage administrative tasks. If I were an auto mechanic no one would propose that I learn to master a casting foundry and a milling machine in order to work on cars, those are clearly manufacturing/development tools AND certainly no good mechanic would suggest that using a wrench to fasten a nut to a bolt is "a hodge podge of ancient idioms" which should be replaced with whatever flavour of the week fastening system and power tool happens to be popular at the moment.

      Sure there are some arcane aspects to shell scripting, but when I learned Unix in college they taught a thing called "the unix philosophy" which basically said that you should always use the smallest tools for the job, leverage the pipes/redirection, and build to a usable script which doesn't replicate existing functionality of ubiquitous tools. Seems like these days every python/perl wizard around fancies themselves an administrator and yet they waste a large portion of their time rewriting tried and true unixisms; sort, wc, cut, paste, tee, etc...

      Also, get off my lawn!

      --
      -*The above statement is printed entirely on recycled electrons*-
    31. Re:If you have a choice... by Pope+Raymond+Lama · · Score: 1

      Oh yes?
      How about counting each time a shell script has to spawn a separate process and python can do the job inside it?
      And what when you stack together 5 such scripts?

      Beyond maintainability, readability, sanity, one can also have some gains in speed and memory usage by using python;

      --
      -><- no .sig is good sig.
    32. Re:If you have a choice... by seebs · · Score: 1

      sed -n -e '// {
      s/.*\(.*\).*/\1/p
      }' musicbrainz.txt

      Of course, I think yours is skipping the first one; maybe it's an album title? I leave fixing that as an exercise to for the reader. :)

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    33. Re:If you have a choice... by seebs · · Score: 3, Informative

      sed -n -e '/<title>/ {
      s/.*<title>\(.*\)<\/title>.*/\1/p
      q
      }' < musicbrainz.xml

      Forgot that "plain old text" isn't. (To verify I had it right, of course, I pasted it into a file with the original and then ran
      !sort | uniq)

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    34. Re:If you have a choice... by chthonicdaemon · · Score: 1
      I see nothing wrong with my natural progression:
      1. execute commands once-off in the shell
      2. paste said commands to a file to execute later once I see they work
      3. pretty up the commands
      4. rewrite in Python
      5. rewrite parts in some compiled language if things are too slow
      6. wrap a GUI over parts of it if other people need to use it

      .

      The advantages are rapid prototyping, and many places to stop putting work into the project without losing functionality. If you have a really well defined large project, big design up front makes sense, but shell scripts tend to grow out of "man, that's like the third time today I had to build that pipeline, let's save it". Now, of course, the scripts are brittle and don't give good feedback on what exactly went wrong, but the tasks they do are not so time consuming that it justifies creating a well-written program to do them.

      --
      Languages aren't inherently fast -- implementations are efficient
    35. Re:If you have a choice... by ultrabot · · Score: 1

      Does python can really replace shell scripting ?

      Yes, for everything apart from script you run with 'source' that manipulate the environment directly.

      I'd really like to know. When I write scripts, I use intensively pipes and awk.

      Would python allow me to do the same kind of things that awk do ?

      Yes, you can call out for a shell by using os.system, os.popen, subprocess module.

      I do think awk is pretty redundant though.

      --
      Save your wrists today - switch to Dvorak
    36. Re:If you have a choice... by ultrabot · · Score: 1

      Python doesn't help much over shell scripts without extra libraries, which may or may not be present on any given system.

      What are those extra libraries without which you can't work? Python standard library is absolutely enough for shell script like tasks, both trivial and non-trivial.

      Python has changed incompatibly several times already.

      It's actually quite rare. Python 3.0 was created explicitly to allow breaking of the compatibility. If you write scripts that use the new stuff, of course they won't work on older scripts. But old scripts still work on new python 2.x interpreters.

      Or do you have a concrete example in mind?

      Python has a large startup overhead:

      So a 0.02 second startup time is a problem for you? If you are starting zillions of python interpreters, you are doing something very wrong.

      Python is not the same syntax as the shell. If you don't learn the shell then your day-to-day command lines are gimped.

      Of course you should learn the shell, and shell scripting as well (to some degree). You still need to be able to read and modify shell scripts, unfortunately. Just don't write new ones that you publish (as opposed to using them for private things).

      Ruby is actually much better... since it has a sensible syntax you could make a rubysh that wouldn't suck.

      If you care so much about performance, I'm surprised you bring up ruby ;-). It's not really "much better" even if your friend moved to it from perl - it's just something some people pick up because they heard a cousin of their friend was once bitten by python's indentation rules.

      --
      Save your wrists today - switch to Dvorak
    37. Re:If you have a choice... by ultrabot · · Score: 1

      And then the whole script goes wildly crazy because it ends up in an unanticipated state? Sounds delicious.

      There's times to abort in the face of error... and times not to.

      The idea with exceptions is that it doesn't happen. Unless you supress the exception, your whole script aborts with a traceback that tells exactly what went wrong. With shell scripts, you get error status and a cryptic error message if you get lucky.

      I'm a lazy bastard, and I've found this to be the perfect behaviour.

      --
      Save your wrists today - switch to Dvorak
    38. Re:If you have a choice... by Anonymous Coward · · Score: 1, Interesting

      It describes most IT environments in large corporations. I've never seen Python installed on Solaris boxes unless they were running Cognos. And I've never seen Python on HP-UX, AIX or IRIX boxes either. That's why the "portable" part in the article title is important. Too many people on slashdot without "enterprise" experience assume the software in their Linux distros is installed on all UNIX systems. I've had to deal with "network appliances" running a specialized, proprietary UNIX-like OS that have Bourne shell, vi, and not a whole lot else. Installing Python is not even an option.

    39. Re:If you have a choice... by Capt+James+McCarthy · · Score: 1

      Shell scripts have horrible error handling, and quickly become a maintenance nightmare. These days, e.g. Python is installed everywhere you need to go.

      That's exactly what the Perl people said years ago, and we all know how well that worked out (for low maintenance sysadmin-type tasks). I know the sinking feeling I get every time I find a crontab entry pointing to a Perl script.

      It's only a 'maintenance nightmare' if you write it poorly. Once it is working and the input isn't altered beyond your vision of possibilities when you wrote it, you should never have to touch those scripts again. Regardless of which you chose.

      Being a minimalist, shell is where it's at. Though Perl is a close second with it's strong parsing capabilities.

      I always wondered if someone has the same (read identical) script on a *NIX system and a Windows system. Then the question would be why?

      --
      There are no loopholes. It's either legal or it's not.
    40. Re:If you have a choice... by RichiH · · Score: 1

      > Python and Ruby have the functionality of Perl without the maintenance issues inherent in a language which is really a hodge-podge of ancient unix idioms.

      It seems to me that Perl 5 (and thus the syntax) has lived a lot longer than Python 2. I won't drag out sh scripts which are still running after a decade or two as that would be unfair ;)

    41. Re:If you have a choice... by Anonymous Coward · · Score: 0

      Thanks, I'll try your scripts when I get home today. However, mine is more readable. ;)

      Yes, the first line is an album title.

    42. Re:If you have a choice... by 0xABADC0DA · · Score: 1

      Ruby is actually much better... since it has a sensible syntax you could make a rubysh that wouldn't suck.

      If you care so much about performance, I'm surprised you bring up ruby ;-). It's not really "much better" even if your friend moved to it from perl - it's just something some people pick up because they heard a cousin of their friend was once bitten by python's indentation rules.

      23s: 1000x ruby -e 'printf("test\n");'

      Ruby's startup time is the same as Python. Both are too slow for many things small shell scripts are used for, which contrary to your belief often do get run thousands of times.

      Your beliefs that shell scripting is never appropriate, that python's syntax is not an impediment, and that Ruby is 'slow' compared to Python are not based on facts, they're based on ignorance.

      Good day, sir.

    43. Re:If you have a choice... by ultrabot · · Score: 1

      Ruby's startup time is the same as Python. Both are too slow for many things small shell scripts are used for, which contrary to your belief often do get run thousands of times.

      It's a design choice that they get run thousands of times - the same design choice would be very bad programming when done in ruby/python scipt.

      Your beliefs that shell scripting is never appropriate, that python's syntax is not an impediment, and that Ruby is 'slow' compared to Python are not based on facts, they're based on ignorance.

      Ok, you convinced me with this argument.

      --
      Save your wrists today - switch to Dvorak
    44. Re:If you have a choice... by Anonymous Coward · · Score: 0

      Parsing XML as plain text is a Very Bad Thing to do. If it's XML, you should use an XML parser to parse it, since everything else *will* fail at some time. And unlike shell fanatics, people using non-toy languages tend to understand that, while shell fanatics don't even seem to get that cat file | do_stuff is *always* stupid (since it should be done via do_stuff < file, or even do_stuff file for lots of utilities (including sed)).

      Of course you can handle xml properly with the shell, because somebody has taken the time to write a tool in a less stupid language that will make this possible. This will read a musicbrainz file from stdin and print the titles, the proper way:
      xmlstarlet sel -N d="http://musicbrainz.org/ns/mmd-1.0#" -t -m "/d:metadata/d:release/d:track-list/d:track/d:title/text()" -v . -n musicbrainz.xml

    45. Re:If you have a choice... by Anonymous Coward · · Score: 0

      Yeah, except that it doesn't work.
      for x in `seq 1 3`; do { echo $x; false } done

    46. Re:If you have a choice... by Anonymous Coward · · Score: 0

      My, my, my. Somebody has quite the superiority complex, doesn't he?

      Parsing XML as plain text is a Very Bad Thing to do.

      Not when you're writing a quick and dirty script, which I plainly stated in the above post. To clear this up, my script won't fail until they change their format. It's worked for years over hundreds of different albums (which I tag all in one batch via my custom tagging system, written in shell).

      people using non-toy languages

      He writes off an entire world of useful functionality (and quite often the best tool for the job) because he's just too good!

      cat file | do_stuff is *always* stupid

      I do this so I can iterate through the pipe on the command line, step by step, building the pipe one piece at a time. I am well aware of the different methods of accepting stdin, and the fact that it wouldn't make a dime's worth of difference in what I'm trying to achieve here.

      a less stupid language

      If you honestly believe that shell programming is useless, then maybe it's you who needs to do a little homework. Make that a lot of homework.

      Anyway, I would say thanks for the example script, but you don't deserve it.

    47. Re:If you have a choice... by Anonymous Coward · · Score: 0

      Not when you're writing a quick and dirty script,

      Writing a dirty script is the wrong thing to do in the first place. Personally, i just prefer writing quick, clean scripts.

      I do this so I can iterate through the pipe on the command line, step by step, building the pipe one piece at a time.

      Shell syntax also allows < file do_stuff.

      If you honestly believe that shell programming is useless,

      I do. The shell was designed to be a *user interface*, not a programming tool, and as such, it is utterly inadequate for any kind of serious development work. The UNIX shell is a pure legacy thing, and the sooner it dies, the better.

    48. Re:If you have a choice... by eloki · · Score: 1

      Works here, I see just the number 1 being echoed, and then the script exits with status 1.

    49. Re:If you have a choice... by Anonymous Coward · · Score: 0

      Huh? That can be done simply with pkill spam. I agree with your general point though, text streams are not an apporpriate IPC mechanism.

    50. Re:If you have a choice... by fava · · Score: 1

      Perl is a language that can be written at many levels. If you use every shortcut and every default action then you are going to get a program that only an expert can decipher. However by avoiding all the little tricks you can create code that is clear and understandable even by someone who has limited experience with perl.

      Until you start with regular expressions, then all bets are off.

  5. Python still can't replace quick scripting by Chris_Jefferson · · Score: 3, Insightful
    While I find anything I want to be stable and distributable I now write in Python, I still can't resist pulling out shell scripting, and a splattering of grep, awk, find, mv and xargs to do 95% of the simple pushing around and chopping up of files I find myself doing every day.

    I find shell scripting have a nasty habit of not working quiet right when moved between Linux, the BSDs and Mac to be safe, and it's always a pain to write scripts that work correctly with spaces in file names.

    Why isn't there (or is there?) a simple python cheat guide, or library, that do the same things as grep, awk, find, mv and xargs?

    --
    Combination - fun iPhone puzzling
    1. Re:Python still can't replace quick scripting by ultrabot · · Score: 3, Informative

      Why isn't there (or is there?) a simple python cheat guide, or library, that do the same things as grep, awk, find, mv and xargs?

      re.findall, s.split(), os.walk, shutil.move,
      " ".join

      --
      Save your wrists today - switch to Dvorak
    2. Re:Python still can't replace quick scripting by ultrabot · · Score: 1

      Why isn't there (or is there?) a simple python cheat guide, or library, that do the same things as grep, awk, find, mv and xargs?

      Forgot to mention - no need to do it all in raw python. Just call out to shell when you feel like it, if you are sure it can stay unix-only. You can do wonders with some shell invocation + os.popen(...).read()

      --
      Save your wrists today - switch to Dvorak
    3. Re:Python still can't replace quick scripting by Anonymous Coward · · Score: 0

      it's always a pain to write scripts that work correctly with spaces in file names

      Well, the only time you would run into those is if you're dealing with a Windows filesystem. That is, unless you use spaces in filenames on a unix-type system. You wouldn't do such a nasty, dirty thing, would you? ;)

    4. Re:Python still can't replace quick scripting by Anonymous Coward · · Score: 0

      I was just getting ready to say, Python is essentially a shell scripting language on steroids. I don't write bash scripts anymore, and its nicely portable between various *NIXes. It's a nice replacement for batch and vbs on windows too.

    5. Re:Python still can't replace quick scripting by Anonymous Coward · · Score: 0

      It's always a pain to write scripts that work correctly with spaces in file names.

      Step 1: change the name of files and insert a character like an underscore.
      Step 2: process the files as normal.
      Step 3: add the spaces again.

      Remove the space; change the sed statement to add the space back into the file name.

      for i in *
      do
                      NEWNAME=`echo $i | sed -e 's/ /_/g' | tr -s _`
                      if [ $NEWNAME = $i ]
                      then
                                      echo "File name $i already exists, cannot rename."
                      else
                                      echo "Moving $i to $NEWNAME"
                                      mv "$i" $NEWNAME
                      fi

      done

  6. Hardly Need a Whole Book by Anonymous Coward · · Score: 0

    Want your shell to be portable? Write it in Korn Shell. You will find this shell on 15 year old *NIX boxes and the script will still work with bash on Linux.

    1. Re:Hardly Need a Whole Book by MrEricSir · · Score: 0, Offtopic

      Korn had some cool videos, but I was never a fan of their music.

      --
      There's no -1 for "I don't get it."
    2. Re:Hardly Need a Whole Book by CannonballHead · · Score: 4, Informative

      It's true. I work with a guy (rather old himself) that writes on the Korn shell because it's the only shell that is included on pretty much all Unix based OSs, including Linux. (and Solaris, HP-UX, and AIX, which we also use).

    3. Re:Hardly Need a Whole Book by seebs · · Score: 2, Insightful

      Sounds great.

      Now, off the top of your head, what happens to variables set in the last component of a pipeline in ksh? Do you know whether it's the same on systems where "/bin/ksh" is actually pdksh? ... Oh, and just for reference, about half the Linux systems our IT department installs don't have ksh. No, I don't know why. (I only know because I can't log into them because my default login shell is /bin/ksh...)

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    4. Re:Hardly Need a Whole Book by multisync · · Score: 1

      Korn had some cool videos, but I was never a fan of their music.

      But you gotta love that mic stand H.R. Giger created for Jonathan Davis.

      --
      I don't care why you're posting AC
    5. Re:Hardly Need a Whole Book by Anonymous Coward · · Score: 0

      Just had to reply with this

      Korn meets KoRN

    6. Re:Hardly Need a Whole Book by wkcole · · Score: 1

      Want your shell to be portable? Write it in Korn Shell. You will find this shell on 15 year old *NIX boxes and the script will still work with bash on Linux.

      Except when it doesn't.

      There are differences between bash and ksh, and between different versions of ksh. In some cases the difference means syntax errors, but sometimes it can be more subtle and a script written for ksh runs just fine but doesn't do in bash what it did in ksh, or doesn't do in pdksh what it does in ksh88.

      It is also not the case that ksh exists everywhere. It wasn't on MacOS until 10.4. It isn't on FreeBSD by default. It isn't on many Linux boxes, particularly the small network devices that use stripped-down systems. If you don't work in a broad variety of systems you may not need to understand the issues of shell portability, but if you don't understand them you aren't really prepared to work on different sorts of systems.

    7. Re:Hardly Need a Whole Book by tbuskey · · Score: 1

      ksh isn't part of Linux normally. Sometime's it's pdksh and sometimes it's genuine AT&T ksh. Same with cygwin. You have to explicitly add it too.

      I had to port some shell scripts from Ultrix to SunOS, Solaris, HP-UX, Irix and OSF/1. ksh wasn't part of SunOS. However, we had bought a license for ksh and put it in /bin/ksh everywhere.

      I needed functions and Ultrix /bin/sh didn't have them. IIRC /bin/sh5 (?) did.

      Anyways, ksh had to be licensed back then. This was Linux 1.09 era. pdksh wasn't even close to being a substitute. bash was 1.x.

      Also, sometimes /bin/sh is ash.....

    8. Re:Hardly Need a Whole Book by seebs · · Score: 1

      Exactly -- you can't just "write for ksh", and even if you do, it's not universal.

      You can do pretty well writing for a common subset of ksh88/pdksh, but I'd rather do the extra few minutes' work and write for plain old POSIX shell by default.

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
  7. Shell scripts are a glue language by pieterh · · Score: 5, Insightful

    One does not write a web server in Bash, one wraps a webserver in it, pipes its output to a log analyzer, restarts it automatically if it crashes, and so on.

    The most important part of any UNIX-derived shell langauge is not its syntax or power but the fact it lets you construct large ad-hoc applications out of a toolbox of tens of thousands of pieces.

    This is where all other operating systems (that I've ever used, and that's 30-40) have failed.

    Any serious developer should know several glue languages, Unix shells being the most flexible and accessible.

    1. Re:Shell scripts are a glue language by seebs · · Score: 4, Funny

      Wow. That's a really brilliant question.

      Wouldn't it have been cool if someone had written a book on the common ground of the major shells covering how to use them as a single highly-accessible and universally-available language? :)

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    2. Re:Shell scripts are a glue language by dgatwood · · Score: 4, Interesting

      One does not write a web server in Bash

      I accept your challenge. :-D

      But seriously, yeah, you're absolutely right. Ooh, but a basic web server written as a Bourne shell script called by inetd would be so freaking cool....

      Oh, no. Somebody actually did that.... Yikes! Now I'm scared.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    3. Re:Shell scripts are a glue language by ClosedSource · · Score: 1

      "The most important part of any UNIX-derived shell langauge is not its syntax or power but the fact it lets you construct large ad-hoc applications out of a toolbox of tens of thousands of pieces."

      What's the advantage supposed to be? Constructing a "large ad-hoc application" doesn't sound like a great idea to me.

    4. Re:Shell scripts are a glue language by seebs · · Score: 4, Funny

      I think "One does not write a web server in Bash" is like "One does not simply walk into Mordor." You're practically daring short people with hairy feet to attempt it.

      But your point is basically good. :)

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    5. Re:Shell scripts are a glue language by starfishsystems · · Score: 1

      But it's reasonable, indeed fairly elegant, to write a web server in Tcl. And Tcl was specifically conceived as a glue language. It doesn't hurt that Tcl commands look a lot like interactive shell commands, but expressed in a more regular syntax.

      I'm mentioning this just to point out that these distinctions of granularity are a bit artificial. Yes, glue languages give you composability at the coarse end of the scale. But they're often quite acceptable as programming languages as well.

      --
      Parity: What to do when the weekend comes.
    6. Re:Shell scripts are a glue language by seebs · · Score: 4, Interesting

      One of the points might be that there's a fairly specialized task which takes a person six hours to do, but which is NEARLY all done automatically -- just a bit of hand twiddling.

      Lemme give an example that isn't portable. One of the things I do fairly frequently is take about six large toolchains distributed to me as binaries and source tarballs, and turn them into patches against upstream versions, reorganize them, delete some unused files, create configuration files that refer to the binaries, generate md5sums, and so on.

      This is a task which, if I sit down at 10AM and start typing, is usually done by about 4PM. Testing takes a bit longer, and usually uncovers SOME kind of typo or thing I forgot to do.

      Enter the shell script.

      I tell the script where the files are, and I walk away. An hour later I have the results. Testing is also automated (another script). But testing is also uneventful, because the script never forgets a step, makes a typo, or otherwise screws up.

      By the second time I did this, the script had saved me time. By the third, it had saved me close to a full working day. By now it's closer to a week of my time that wasn't spent messing with this stuff.

      Portability isn't entirely crucial here, you might think? Well, not ENTIRELY crucial, except that when they had me start doing this on a new box running a different variety of Linux, the total time I spent revising the script was 0 minutes.

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    7. Re:Shell scripts are a glue language by Eil · · Score: 1

      One does not write a web server in Bash

      Uh oh. Someone should have warned this guy.

    8. Re:Shell scripts are a glue language by Bob+The+Cowboy · · Score: 1

      I think "One does not write a web server in Bash" is like "One does not simply walk into Mordor." You're practically daring short people with hairy feet to attempt it.

      Yeah but Linus is already working on the kernel...

    9. Re:Shell scripts are a glue language by fm6 · · Score: 1

      The most important part of any UNIX-derived shell langauge is not its syntax or power but the fact it lets you construct large ad-hoc applications out of a toolbox of tens of thousands of pieces.

      Like constructing a Windows app out of ActiveX components?

      No, I'm not saying that ActiveX is as good a glue as the Unix equivalents, or that Windows is as good as Unix. I'm just saying that there's more to Unix than its ability to glue stuff together.

      This is where all other operating systems (that I've ever used, and that's 30-40) have failed.

      I guess your definition of "failure" is "Pieter hates using it". By any other measure, there are are fair number of non-failed OSs that aren't Unix or Unix-like.

    10. Re:Shell scripts are a glue language by ClosedSource · · Score: 1

      I can see the value of shell scripts for small or possibly medium size ad-hoc applications but not for large ones.

    11. Re:Shell scripts are a glue language by pieterh · · Score: 1

      By "failed operating system" I was referring to the dozens of mini computer OSes that were tried, and abandoned, in the 80's and 90s. Unix succeeded mainly because it was open source, and because it was built on the philosophy of making it easy to build new things out of old ones. That 100-line web server looks like it's a shell script but in fact it's based on a number of small, reusable pieces like nc.

      Windows was not one of the failures I was thinking of. Rather, systems like DG/AOS, VMS, VM/CMS, DOS/VSE, etc. All workable up to a point, none ever became an ecosystem. Since you bring up Windows, it does not at the shell level offer more than a weak imitation of the UNIX model. But it does offer something similar to developers starting with languages like VB, and ActiveX, which is a large part of why it succeeded.

      Sorry to disappoint, but I'm not a Windows hater, and am right now building a bunch of my open source on Windows using the free Microsoft C compiler. I just won't use Windows for my real work because it is the wrong tool for me as a serious developer.

    12. Re:Shell scripts are a glue language by pieterh · · Score: 1

      If you read that web server script you'll see it's exactly as I described, an application built out of existing pieces: nc, sed, head, ls. Try doing this on any other OS, and it becomes obvious why the Unix metaphor is still so popular after something like 30 years.

      The amazing thing here is not that we can write web servers in shell scripts. It's that we're still using software tools that were designed and were mature before many of us here were born.

    13. Re:Shell scripts are a glue language by RichiH · · Score: 1

      Maybe not a web server, but there are ftp and irc clients written in zsh. Having a native ztcp helps, of course :)

    14. Re:Shell scripts are a glue language by drinkypoo · · Score: 1

      Actually, the atomic and redirectable nature of programs IS a key feature of a Unix system. Lots of people have made command-line programs for Unix which break the metaphor, for example by requiring that you use them interactively. These people are dumb, and are fucking it all up for the rest of us. Redirection and multitasking is the solution to temp files and job control. To omit one or the other is to completely miss the point of Unix. If you have redirection without multitasking, you have DOS which actually makes temp files when you pipe, because it only runs one program at a time. STDIN doesn't mean on DOS what it means, you know, in places where it is real. To omit redirection but to have multitasking is to have, I dunno, MacOS9 or something. Dum de dum dum dum. And by "failed" it's clear that the parent author is saying "failed to not suck". I think we (mostly) all agree Windows is pretty lame, but lots of people still use it.

      --
      "You're right," Fisheye says. "I should have set it on 'whip' or 'chop.'"
    15. Re:Shell scripts are a glue language by fm6 · · Score: 1

      You said that all the operating systems you've ever used have been failures, except for Unix. I read that to be an assertion that non-Unix OSs in general have been a failure. If you're only talking about the ones you've worked with, then you're really talking about your poor luck with OSs, not about Unix's general superiority.

    16. Re:Shell scripts are a glue language by seebs · · Score: 1

      Large is relative. Compared to tr, grep, and sort, all sorts of things are "large".

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    17. Re:Shell scripts are a glue language by sfsetse · · Score: 1

      Try shUnit2 for shell unit testing! http://code.google.com/p/shunit2/ - kate

  8. PSS can be a recurring problem by Anonymous Coward · · Score: 3, Insightful

    I'm sure all of us at one time or another have had a shell script we've relied on for years fail miserably when bringing it to a new environment. The sad fact is, shell scripts were never meant to be programming languages in and of themselves, and I wonder if, knowing what we know now, it isn't overly ego-driven and masochistic to try to take this feature -- tied to a shell which is tied to an operating system -- and promote it beyond its competency.

    So, let's say we take the PSS principles seriously, and abstract away any non-platform-agnostic features you can think of. A few years down the road, you've got PSS all over the shop and you want to upgrade to a different platform nominally supporting your shell of choice. Even if you shake off PSS features you thought could create incompatibilities, you discover the new system buffers differently. Or added a parameter somewhere. Point is, if you went with something like Perl which is designed for cross-compatibility you would have been fine, but now you're all wet.

    Shell scripting is good for what it's meant for, but at the risk of oversimplifying with a tool analogy, I'm concerned that this falls into the trap of "If all you have is a hammer, all your problems look like nails".

    1. Re:PSS can be a recurring problem by seebs · · Score: 1

      You know, that's exactly why a book on it is useful -- because it turns out that you can, in fact, write scripts which port quite nicely.

      Seriously, "buffers differently"? What's THAT supposed to mean?

      That said, I won't deny for a moment that there are things shell isn't a good choice for. In fact, one of the first sections in the book is under the heading "What Shell Scripting Isn't". Because sometimes the best way to write a good program is to pick the right language to begin with. Often, even.

      But sometimes, that language IS shell.

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    2. Re:PSS can be a recurring problem by Alpha830RulZ · · Score: 1

      Seriously, "buffers differently"? What's THAT supposed to mean?

      One example is how and when data gets written to disk in the absence of a flush().

      --
      I was taught to respect my elders. The trouble is, it's getting harder and harder to find some.
    3. Re:PSS can be a recurring problem by seebs · · Score: 1

      And what "flush()" do you expect to see in a shell script?

      You're thinking at a level that generally doesn't apply well to shell scripts. Scripts rarely deal with questions such as "has this been actually written to disk" -- because that's at the wrong level. If you need that information, you shouldn't be writing in shell anyway.

      But normally you don't...

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    4. Re:PSS can be a recurring problem by Eil · · Score: 1

      I agree with your overall message, but...

      So, let's say we take the PSS principles seriously, and abstract away any non-platform-agnostic features you can think of. A few years down the road, you've got PSS all over the shop and you want to upgrade to a different platform nominally supporting your shell of choice. Even if you shake off PSS features you thought could create incompatibilities, you discover the new system buffers differently. Or added a parameter somewhere. Point is, if you went with something like Perl which is designed for cross-compatibility you would have been fine, but now you're all wet.

      Shell scripting is best for system administration and automation. Basically, you wouldn't do anything in a shell script that you couldn't do with some combination of command-line savvy and text editing. Even though the scope of shell scripting is more limited than say, Perl, you still need a relatively full-fledged programming toolkit including variables, conditions, loops, functions, and so on in order to get anything useful done.

      The pitfalls you describe above apply equally to Perl if you try to substitute it for Bash. Bash too is identical on every platform, it's the external commands and environment that differ. We know that keeping even "proper" high-level application code portable across various platforms is quite difficult, so Bash is certainly no exception.

      We have different programming environments and languages for a reason. No one language fits all use cases. My guideline is generally this: If it's a sysadmin task, do it in Bash. If it's an application, talks to a database, or will be used by "normal" users, it's almost always better to use something else.

  9. Free guide to shell scripting by Anonymous Coward · · Score: 0

    If you want a free guide to shell scripting have a look for "Aliens Bash Tutorial" on google

    1. Re:Free guide to shell scripting by zippthorne · · Score: 1

      Not so much a guide, but "man bash"* or "info coreutils" are incredible resources for those common bits you routinely forget. If you stick to what's in coreutils, I think you've got a pretty good chance of portability.

      *for systems that use bash as the shell, of course. Frankly, I think there might be too much in there, though and some of the builtins should have their own man pages.

      --
      Can you be Even More Awesome?!
  10. Oh I hate those [ "X$var" == "X" ] by Nicolas+MONNET · · Score: 0

    Why bother with portable shell scripts, seriously? Everybody has bash installed, and/or zsh that is mostly compatible, and even then you have bash anyway.
    I understand retro-nostalgia and all that, but necrophilia is overrated.

    1. Re:Oh I hate those [ "X$var" == "X" ] by seebs · · Score: 1

      Actually, that's useful in bash too sometimes. :)

      Anyway, the reason I bother is this:

      I wrote a bunch of scripts in 1992 or so. I'm still using them. I haven't touched any of them in years, except for one update to deal with Linux differing from BSD in where the actual errno definitions are.

      I don't have to worry about what shells are installed, I don't have to guess whether bash is "/bin/bash" or "/usr/pkg/bin/bash", I don't have to wonder whether the sysadmin bothered to install the "GNU utilities". I just copy my scripts into ~/bin and go.

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    2. Re:Oh I hate those [ "X$var" == "X" ] by larry+bagina · · Score: 2, Insightful

      Not everybody has bash and/or zsh installed.

      --
      Do you even lift?

      These aren't the 'roids you're looking for.

    3. Re:Oh I hate those [ "X$var" == "X" ] by Anonymous Coward · · Score: 0

      Everybody has bash installed, and/or zsh that is mostly compatible, and even then you have bash anyway.

      The utterances of experts. Now go and try a real traditional Unix -- not Linux, not even OS X, I mean something like Solaris, AIX, or HP-UX. Enjoy hunting for bash or zsh. (Hint: your choice will be between ksh and csh.)

    4. Re:Oh I hate those [ "X$var" == "X" ] by wkcole · · Score: 4, Informative

      Why bother with portable shell scripts, seriously? Everybody has bash installed, and/or zsh that is mostly compatible, and even then you have bash anyway. I understand retro-nostalgia and all that, but necrophilia is overrated

      False.

      The majority of systems I work on these days and the majority of systems I have worked on since the mid 90's have not had bash installed. That includes systems running FreeBSD, NetBSD, OpenBSD, AIX, Tru64, Solaris, MacOS, and even Linux. Current versions of some of those will usually have bash in a default installation, but some still do not. Companies running stable systems as important parts of their business do not generally upgrade their OS's just for the sake of novelty. Running older systems isn't usually about nostalgia or necrophilia, it's more often about not having any compelling reason to upgrade. There is also a system hygiene practice common on the BSD's of keeping the base system minimal and only adding on what is needed, a practice that helps in keeping systems secure and stable because they are easier to fully understand. This is also common in many virtualization environments, where a running OS instance is likely to exist for a very narrow purpose and intentionally have a stripped-down set of utilities fit to that narrow purpose.

    5. Re:Oh I hate those [ "X$var" == "X" ] by Nicolas+MONNET · · Score: 1

      Recent versions of MacOSX have bash by default. By recent I mean 10.4 had bash, and probably 10.3 but I'm not sure.

      All Linux distribs have had bash installed by default for ever. And by all I mean 99.999% of the installed base, I'm sure you can find a silly exception.

      Recent versions of Tru64 ... do not exist.

      As for the BSDs, Netcraft confirms it, .. err. I don't know, what's their default shell?

      And as for Solaris, its default shell -- a Soviet-era knock off of the original Unics v1.0 -- is so fucktarded that nobody in their right mind keeps it as their default shell, and I've always seen bash or zsh instead.

      There is also a system hygiene practice common on the BSD's of keeping the base system minimal and only adding on what is needed, a practice that helps in keeping systems secure and stable because they are easier to fully understand.

      Yeah, you're right, installing such an experimental, little used and unmaintained software package as bash is irresponsible. /facepalm

    6. Re:Oh I hate those [ "X$var" == "X" ] by larry+bagina · · Score: 1

      AIX uses ksh.

      --
      Do you even lift?

      These aren't the 'roids you're looking for.

    7. Re:Oh I hate those [ "X$var" == "X" ] by Anonymous Coward · · Score: 0

      Yeah, you're right, installing such an experimental, little used and unmaintained software package as bash is irresponsible. /facepalm

      Have you ever worked in the UNIX industry at an enterprise level? I work for a company that supports dozens (if not hundreds) of customers UNIX boxes of all different flavours on as many hardware configurations (AIX 4.x.x-6.x.x, Solaris 6-10,HP/UX, IRIX, Tru64 etcetc), and I couldnt count five servers from all of these that have bash installed.

      It simply isnt done, you dont install things that dont need to be installed. This includes bash. Python quite often too, sometimes its installed for another application, but quite often not.

      Of course, most of the modern releses come with bash by default, but generally the default shell is still ksh. ksh is still the standard in the industry, as much as bash is 'better'. I remember starting this job, opening my first terminal and after realising it was in ksh I tried `bash` -> ksh: bash: not found. I wept a little, but you get over it and get used to it.

      Hell, just to test it I jumped on one of our AIX testing boxes running a reasonably new release. This is a box that engineers jump on to test and break quite often (there are no rules against installing whatever you want on these boxes). We have around 30 engineers, probably 10 of which are near purely AIX based. If bash was so common, it would be installed, right?


      root@SVXAPMEL201:/ # oslevel -r
      5300-06
      root@SVXAPMEL201:/ # uname -a
      AIX SVXAPMEL201 3 5 00---------
      root@SVXAPMEL201:/ # bash
      ksh: bash: not found.
      root@SVXAPMEL201:/ # which bash
      which: 0652-141 There is no bash in /usr/bin /etc /usr/sbin /usr/ucb /usr/bin/X11 /sbin /usr/java14/jre/bin /usr/java14/bin.
      root@SVXAPMEL201:/ # find . -name bash
      root@SVXAPMEL201:/ #

      (The server was built off a customers mksysb, hence the server name. Their environment is Power6 LPAR'd up the wazoo, theyre running 5.3-06 because of an application limitation I believe. And yet, still no bash)

      After my time in the industry, pretty short in comparison to most, I now much prefer ksh+vi over bash. Whenever I encounter a bash shell I get a little confused, and instantly $ set -o vi to feel more comfortable (and have far more control than the default bash allows). You need to learn ksh over bash simply because you cannot trust a system to have bash installed. If you prefer it, hey, a nice suprise every once in a while, but most of the time you're stuck in the world of ksh

    8. Re:Oh I hate those [ "X$var" == "X" ] by wkcole · · Score: 1
      I think you failed to notice the context...

      Recent versions of MacOSX have bash by default. By recent I mean 10.4 had bash, and probably 10.3 but I'm not sure.

      10.3 had it. Prior versions did not.

      All Linux distribs have had bash installed by default for ever. And by all I mean 99.999% of the installed base, I'm sure you can find a silly exception.

      A large fraction of the Linux systems I work with are embedded versions which use things which seem to be descended from the BSD (Almquist) sh. Talking about installed base numbers is silly, because it is probably also true that 90%+ of those systems have never been seen by a competent sysadmin who has any intention of ever using anything Unixy that isn't a major Linux distro. They might as well be Windows for all of the relevance of portability....

      Recent versions of Tru64 ... do not exist.

      Obviously you are not paying attention. There was a 5.1bsomething maintenance release by HP in the last few months, and they have said that they will continue support through 2012. Whether the current version has bash I don't know, but in the real world there are still major companies running 4.0f, which I am absolutely sure does not have bash. I would not suggest the project of installing bash on Tru64 4.0f to anyone I liked.

      As for the BSDs, Netcraft confirms it, .. err. I don't know, what's their default shell?

      FreeBSD uses the Almquist sh and I expect the others do as well. The product of Bourne sh and ksh procreating while watching kinky csh porn...

      And as for Solaris, its default shell -- a Soviet-era knock off of the original Unics v1.0 --

      Hardly a knockoff. That's the real Bourne Shell, built with genuine AT&T code.

      is so fucktarded that nobody in their right mind keeps it as their default shell, and I've always seen bash or zsh instead.

      Which is a career-limiting choice on Solaris 9 or earlier if done to root. People who fancy themselves sysadmins have wisely been fired for it. I don't recall if Sol10 includes bash or zsh, but I've never seen an experienced Solaris admin picking either of them for personal use and it is still prudent to stick with sh for scripts that may have to run under odd circumstances and ksh for anything that might get put on a Sol9 box. The selection of a shell for non-root interactive use is far more a matter of personal taste than the selection of what you put after #! on the first line of scripts, particularly ones that need to be functional at bad times.

      There is also a system hygiene practice common on the BSD's of keeping the base system minimal and only adding on what is needed, a practice that helps in keeping systems secure and stable because they are easier to fully understand.

      Yeah, you're right, installing such an experimental, little used and unmaintained software package as bash is irresponsible. /facepalm

      it's not necessarily irresponsible, but why bother? It's one more thing to track, because even if bash hasn't had a real vulnerability identified in a long time, it still could have one tomorrow. It's a little more backup space. It's one more thing to explain to the security auditors who treat every variance from a stock installation as something that needs explaining, on an annual basis. If it's the last Tru64 box with a lot of interactive logins in a largely-linux environment, installing bash makes a lot of sense. For a FreeBSD jail that handles one website, it probably doesn't make sense.

    9. Re:Oh I hate those [ "X$var" == "X" ] by Anonymous Coward · · Score: 0

      The majority of systems I work on these days and the majority of systems I have worked on since the mid 90's have not had bash installed.

      And they had python installed by default? I know bash has been on my solaris, linux and freebsd boxes since the 90s. I don't think we did any special installs for bash or csh.

      Also, I still use bash for my reports, sql dumps, nagios alarms, wrappers, etc. Mostly on production servers that are already deployed and no python and a plain perl install. But bash and gnu tools are always there. Awk here, sed there, wrap it in bash, 10 lines, boom done. And if you cant read bash or say its unreadable, you shouldn't be touching a server. But for longer projects we still use perl.

      Maybe I've been working corporate gigs too long, I'll do use bash, so I dont have to go through change management.. Write a mop with a backout procedure, test it in the lab, get it approved, get it scheduled, and then installed during a maintenance window around midnight, just to use the newest wizbang tool.

      Nah, I'll keep using Bash.

  11. Get ur histry right fella! by Anonymous Coward · · Score: 0

    DOS emulates Gary Kildal's CP/M .. CP/M got it from the Digital Equipment VAX .. they got it from the original UNIX/ATT. .. talk about copyright theft!

    IBM came up with the hierarchical file system.

    --- I was there when it all happened!!

    BTW -- Microsoft stole the mouse and windows from Xerox PARC and DOS from Digital Research!! Neither of these guys chose to sue even though they could have!!

    1. Re:Get ur histry right fella! by quickOnTheUptake · · Score: 1
      Speaking of knowing your history:

      Digital Research threatened legal action, claiming PC/MS-DOS to be too similar to CP/M. IBM settled by agreeing to sell their x86 version of CP/M, CP/M-86, alongside PC-DOS.

      So Digital did threaten, but there was a settlement. DR-DOS on Wikipeida

      --
      Mod points: Guaranteed to remove your sense of humor.
      Side effects may include gullibility and temporary retardation
    2. Re:Get ur histry right fella! by billstewart · · Score: 1

      VMS looked far more like RSTS-11 or RSX-11 than like Unix. I don't know if CP/M was inspired by VMS or by its predecessors. DOS certainly wasn't inspired by Unix, at least in the original versions; they clearly didn't have any of the concepts, even though they had a machine that was almost as powerful as a small PDP-11 and more powerful than an IBM System/34 (which had a quite nice shell), and later versions of DOS (around 3ish?) started emulating some Unix shell syntax while still not having the underpinnings to do the job.

      --

      Bill Stewart
      New Fast-Compression-only CPR http://preview.tinyurl.com/dy575ks
  12. Why Buy? by Monkey_Genius · · Score: 1

    When it's free -as in beer: 'Advanced bash Scripting Guide - Mendel Cooper'.

    --
    I've got your sig, right here.
    1. Re:Why Buy? by seebs · · Score: 2, Insightful

      Well, I suppose because the contents are different. We're answering different questions.

      I would never dream of discouraging people from looking at and using the various free guides out there. The autoconf manual is full of useful information about portability, too.

      There's more than one article or book because there's more than one topic. "Shell Scripting" is not a single topic; "portable shell" is very different from "advanced bash". It solves different problems, and is useful for different circumstances.

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    2. Re:Why Buy? by dfn_deux · · Score: 1
      Thats one of my favorite references works, but the second you try and use one of those clever bashisms you've gone right off the deep-end of portability. Arrays and substring variable references are good and powerful things to use, but good luck making a script that depends on them run under a regular posix bourne shell... try this on bourne for instance:

      x="blah"
      y=0
      function moo(){
      while [[ ${y} -le ${#1} ]]; do
      output=${1:$(( y++ )):1}
      echo ${output}
      done
      }

      foo=( "`moo ${x}`" )
      count=0
      if [[ ${#foo[*]} ]];then
      echo 'it worked'
      fi

      --
      -*The above statement is printed entirely on recycled electrons*-
  13. Just some general comments... by seebs · · Score: 5, Informative

    First off, in the interests of full disclosure, Joe MacDonald is one of my coworkers.

    Anyway... The big surprise to me was the word "Beginning", which somehow showed up in the publisher's cover pages, but which I didn't know about during the writing process. My tech reviewer was Gary V. Vaughan (yes, the autoconf/libtool guy). I bounced material off a number of seasoned expert scripters during the process. Basically, my goal was to write a book that I could use as a reference, and which would teach me something.

    I succeeded beyond my wildest dreams. The discovery that printf(1) is essentially universal these days was a complete shock to me; I had no idea it was portable. During my first pass on the regular expressions section, I started by writing down what I believed I knew about sed, awk, etcetera. Then I tested it... and had to revise most of it. A number of things I was used to were GNU or BSD extensions. When Gary sent the chapter back for tech review, he'd flagged most of these things, because he "knew" the same things I did.

    So everything there should be pretty thoroughly checked out now -- I realized very early on that this field was full of things "everyone knows". Many of them wrong. We tested things on a field of around 30 different versions of Unix and Linux. We tested them on unusual installs, we tested them on special cases.

    Why?

    Because portable shell is an incredibly portable language, and sometimes that matters. Because shell is a very powerful language, too. Because sometimes shell is all you have -- and because sometimes shell is more expressive for a task than your other choices. I love me some C, I program in C by preference much of the time -- but there are a lot of tasks I'll do in shell rather than in C. There are similarly many tasks I'd rather write in shell than in perl. Shell is what make uses to run commands, and sometimes you need to write something clever in shell because make doesn't have quite the right feature.

    In short, it's something I have found consistently useful, day in and day out, for about twenty years now. I just wish I'd realized how much more there was to learn years ago, I coulda saved a lot of time... :)

    And, to answer a question hinted at earlier: Yes, now that this book exists, I keep a copy on my desk. I look stuff up in it about once a week.

    --
    My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    1. Re:Just some general comments... by Anonymous Coward · · Score: 0

      In the interest of full disclosure I don't know Peter or Joe

      I just ordered the book. Those that don't see the value of the book are the missing the fundamental design decisions that make unix unix. They also probably don't know how much they rely on shell scripts written by others.

      Those that read your explanation regarding testing for portability and instill insist that shell scripts aren't portable obviously are missing the point.

      I'm excited about the lengthy explanation of the historic design decisions that make shells what they are today. I'm sure that this book will enhance troubleshooting skills.

      Thanks to Joe for the review and peter for the book.

    2. Re:Just some general comments... by seebs · · Score: 1

      Thanks for the feedback. Hope you enjoy the book!

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
  14. Re:Shell scripts are a glue language...to some by Anonymous Coward · · Score: 0

    One does not write a web server in Bash, one wraps a webserver in it, pipes its output to a log analyzer, restarts it automatically if it crashes, and so on.

    Well said, if you limit your scope to publishing web pages. Many servers have other insignificant purposes, but hope to grow up to be web servers someday.

  15. portable shell scripting is called Python by fuzzylollipop · · Score: 1, Redundant

    why deal with limited shell scripting when you have something so batteries included and universal as Python

    1. Re:portable shell scripting is called Python by seebs · · Score: 1

      Honestly, I just never got into python. I like perl (and hate it), and I like Ruby (and love it), but Python never "clicked" for me. Python and Tcl are the "scripting languages I just don't enjoy working in".

      But... I also don't have it on everything I use. And I could get it, but that's another distraction from Getting The Job Done. So I do a ton of work in shell. Especially work that's entirely built around running other commands.

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    2. Re:portable shell scripting is called Python by Anonymous Coward · · Score: 0

      which version of this universal python do i need?
      which supplementary libraries for this universal python do i need to install?

    3. Re:portable shell scripting is called Python by ultrabot · · Score: 1

      Honestly, I just never got into python. I like perl (and hate it), and I like Ruby (and love it), but Python never "clicked" for me. Python and Tcl are the "scripting languages I just don't enjoy working in".

      I believe this is a common mindset issue. Ruby borrowed lots of stuff from perl (which they thought was good, or appealing to convert - I'm not sure), including TIMTOWTDI, whereas Python community thinks of Perl as a warning example more than anything else. My theory is that the different languages balance between simplicity and 'regularity' (python) vs. 'playfullness' and 'interesting' solutions (ruby, perl).

      --
      Save your wrists today - switch to Dvorak
    4. Re:portable shell scripting is called Python by seebs · · Score: 1

      That may be. I find Ruby much better than perl; perl always struck me as inherently ugly. Perl tolerates careful programming and writing for clarity; Ruby encourages it.

      Python felt a bit too constrictive to me, if you'll pardon the pun. And I didn't like the indentation (although I grant the underlying intent, I just don't think it pays off enough).

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    5. Re:portable shell scripting is called Python by wdef · · Score: 1

      Every programmer I meet seems to be into Python. I am probably going to have to learn Python. It's a bit depressing because it is YAS (Yet Another Syntax). Sigh. I don't mind Perl at all, though I feel it could take 10 years to really master Perl.

    6. Re:portable shell scripting is called Python by dugeen · · Score: 1

      If I must move away from Perl then I prefer Ruby to Python. I dislike the way that Ruby and Python both treat whitespace as significant. I hate having to start a block which I'm supplying to .each on the same line as the .each .

  16. Where shell scripts shine by wdef · · Score: 1

    Wherever you want to do an awful lot of things with the input and output of) system utilities and./or bash builtins. Look at the gargantuan effort that is the Knoppix boot scripts - I seriously doubt it would make sense to rewrite those in Python or Perl, since nearly every line is a pipe between utilities or redirection. And it works well.

    1. Re:Where shell scripts shine by ultrabot · · Score: 1

      Wherever you want to do an awful lot of things with the input and output of) system utilities and./or bash builtins.

      Whenever you try to do something nontrivial in between the system utilities, you start losing the benefit of shell scripts.

      --
      Save your wrists today - switch to Dvorak
    2. Re:Where shell scripts shine by wkcole · · Score: 1

      Wherever you want to do an awful lot of things with the input and output of) system utilities and./or bash builtins. Look at the gargantuan effort that is the Knoppix boot scripts - I seriously doubt it would make sense to rewrite those in Python or Perl, since nearly every line is a pipe between utilities or redirection. And it works well.

      I'm not familiar with Knoppix, but that is true for all boot script systems, and beyond being hard to do in something else, there are cases where it may be impossible. There are still systems out there that boot on very small root filesystems that do not have any shared libraries available until the rest of their storage is mounted, so you've got to have something small and statically linked to run the scripts that get your whole software edifice in place. You can have similar problems in some failure states, where you might like to have something run if, say, /usr suddenly vanishes or if root needs to log in on the console of a box that has dropped off the net. There are systems where /sbin/sh exists for just such reasons and is a statically linked classical Bourne shell.

  17. So WHO does not? by Nicolas+MONNET · · Score: 1

    I've heard that said for 15 years, that might have been true 15 years ago, but now ... ?

    1. Re:So WHO does not? by Anonymous Coward · · Score: 0

      Welcome to the wonderful world of slow moving corporate standards.
      I recently left a company that requires a business case for bash shell requests

    2. Re:So WHO does not? by Anonymous Coward · · Score: 0

      The only 'nix-like that seems to have bash as standard is Linux.

      News flash. There are other 'nix-likes.

    3. Re:So WHO does not? by Guy+Harris · · Score: 1

      The only 'nix-like that seems to have bash as standard is Linux.

      $ /bin/sh --version
      GNU bash, version 3.2.17(1)-release (i386-apple-darwin9.0)
      Copyright (C) 2005 Free Software Foundation, Inc.

      "apple" and "darwin" should indicate on what OS I typed that. (10.5.6, if you're curious.)

  18. Nobody's seriously comparing C and shell by Nicolas+MONNET · · Score: 1

    Saying "I love C but there are things that are better in shell" is completely anachronistic.

    Seriously. The question's been settled for over 20 years.

    And there are other languages, you know. The question is more whether to use Python (for example) instead of shell in some cases, and when.

    1. Re:Nobody's seriously comparing C and shell by seebs · · Score: 2, Interesting

      I compare C and shell all the time. Sometimes the answer surprises me. e.g., until I knew about printf(1), I sometimes went to C if I needed to pretty-print output. Now sometimes I don't.

      I will happily mix and match multiple languages; one of my first shipping products was written in shell, perl, and C. Each did some things well that the others didn't...

      I tend not to use Ruby for things that I want to be portable, because not everything has Ruby around yet. I tend to avoid Python because it just never "clicked" for me. I use perl for self-contained programs, but I don't like it very much for code that has to run other commands or manipulate files.

      To this day, I've never found any of the competing languages to be as expressive as shell for things that are essentially sequences of Unix commands. If a task is something I would normally perform sitting at a prompt typing, I tend to find shell to be the language closest to the problem space.

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
  19. One area Python still falls short by clawsoon · · Score: 1
    I've run into one big problem replacing find/xargs in Python: There's no good equivalent of the find '-print0' and xargs '-0' options. Efficient iteration over stdin (or file) lines in Python can *only* use the regular line separator. If you want to write a backup script that uses find instead of os.walk for speed and pump it into Python for convenience, everything breaks as soon as you hit a filename with a newline in it.

    (And no, trying to enforce a "no newlines in filenames" policy doesn't work. Been there, tried that.)

    1. Re:One area Python still falls short by ultrabot · · Score: 1

      I've run into one big problem replacing find/xargs in Python: There's no good equivalent of the find '-print0' and xargs '-0' options.

      This seems to work:

      fs = os.popen('find -print0').read().split('\0')

      --
      Save your wrists today - switch to Dvorak
    2. Re:One area Python still falls short by clawsoon · · Score: 1

      Your idea works until you have a huge number of files (not uncommon for a backup script) and run out of memory on the .read() call. Not pretty. To avoid that, you have to use .readline() or the file iterator, both of which have the newline limitation I mentioned.

    3. Re:One area Python still falls short by ultrabot · · Score: 1

      Your idea works until you have a huge number of files (not uncommon for a backup script) and run out of memory on the .read() call. Not pretty. To avoid that, you have to use .readline() or the file iterator, both of which have the newline limitation I mentioned.

      So, it's back to actual coding then :-). I don't have a oneliner for that, but shouldn't be too hard:

      b = f.read(blocksize)
      spl = b.split('\0') ... do stuff with lines, and reloop

      Always add the last line from the split to the beginning of next block.

      This way, you can make a memory-efficient generator that only allocates data when it needs it.

      --
      Save your wrists today - switch to Dvorak
    4. Re:One area Python still falls short by clawsoon · · Score: 1

      Yeah, I was always too lazy to do that. :-) I figure the Python developers should to it for me in C. (I'd want to benchmark a solution like that, too. How does it do with millions of files?)

    5. Re:One area Python still falls short by Abcd1234 · · Score: 1

      So, it's back to actual coding then :-).

      Or, you could, you know, just use grep, awk, find, mv and xargs.

  20. News flash by Nicolas+MONNET · · Score: 1

    Linux is obliterating commercial Unices.

    It has in part something to do with the backspace key working out of the box without typing "stty erase ^H" every time. (Have they fixed that on Solaris, yet?)

    1. Re:News flash by Anonymous Coward · · Score: 0

      So that's a good reason to write bad non portable code, is it?

      Having an "all-the-world's-an-x86" or an "all-the-world's-a-Linux-box" attitude and relying on it *will* bite you in the end, and you *will* deserve the pain you get from having that attitude.

  21. Sry, I don't do archaelogoy by Nicolas+MONNET · · Score: 1

    I know paleounices suck. Does it matter to 99% of shell writers, is the question.

  22. Bruce Blinn's book already exists, though... by Anonymous Coward · · Score: 0

    Do we really need _ANOTHER_ "Portable Shell Programming"?

  23. Oracle, too... by itomato · · Score: 1

    All the DBA's I have worked with (as well as C programmers worth their salt) have tended to use ksh by default.

    I think Oracle's documentation always uses korn, and maybe I have just worked with a bunch of old IBM'ers..

  24. Python and PHP are forbidden where I work by Anonymous Coward · · Score: 0

    Python and PHP are forbidden where I work. No FOSS allowed, period.

    Perl is allowed, but only the versions provided **with** the OS install and indemnified by the OS vendor. No CPAN allowed.

    I agree with your overall idea, with a slight modification ... don't write large, complex shell scripts. When a shell script gets beyond 2 pages, it's time for a different answer.

  25. /bin/sh by Anonymous Coward · · Score: 0

    It's true. I work with a guy (rather old himself) that writes on the Korn shell because it's the only shell that is included on pretty much all Unix based OSs, including Linux. (and Solaris, HP-UX, and AIX, which we also use).

    /bin/sh is based on the Korn shell actually. I believe it's a subset of ksh.

    The main issue is that on many Linux systems /bin/sh is a link to bash, and bash does not properly separate out functionality between it's "sh" part and its "bash" part. So you get all of these developers who write stuff out on Linux that are full "bash-ism", and they don't test it anywhere, so when you try to run it on BSD or Solaris it fails.

    When Ubuntu changed it's /bin/sh to dash many, many scripts had to be fixed:

    http://en.wikipedia.org/wiki/Debian_Almquist_shell

  26. Going the Other Direction by billstewart · · Score: 1

    My first Unix shell was the Mashey shell that preceded Bourne shell, on a PDP-11 running v6. :-) Before that I'd used RSTS-11, HPUX Basic, the IBM System 34 shell (OCL was fairly powerful, though less than sh), CMS, Plato, and various things with punch cards. Unix shell seemed powerful, flexible, and really really appropriate. I later used other shells like TSO and occasionally CP/M; I forget if I used VMS and ddt before DOS or only after.

    Eventually MS-DOS came around, and it was painfully clumsy. It was like they'd seen Unix on a viewgraph, but hadn't gotten the concepts and had left most of the interesting commands out - they had hardware that was about as powerful as a small PDP-11, dedicated to one user!, and an integrated graphics system as well, and yet the environment was hopelessly lame. There were directories, but they didn't have the same syntax for each level of the file system, there wasn't the equivalent of "cd ..", you could use variables but they were really limited, you couldn't pipe commands together, and of course regular expressions were missing. MS-DOS 2.11 and 3 were better than MS-DOS 1. People claimed it was friendly, but it was almost as bad as being on a punch-card system like JES-3 or HASP except that you had a backspace key.

    A few years later the Macintosh people came around and claimed that _they_ were more friendly than Unix, and they were correct - the system was less powerful, but it really was helpful. VMS was ugly and evil, but it was reasonably powerful, and had a very good help system.

    --

    Bill Stewart
    New Fast-Compression-only CPR http://preview.tinyurl.com/dy575ks
  27. Have you ever tried to use gem? by Anonymous Coward · · Score: 0

    Have you ever tried to use ruby gem?

    Seriously. What a POS. It simply doesn't work for non-trivial needs with less than 512MB of RAM. That's a non-starter in a web hosting environment.

    Gem has nothing on CPAN (which rocks!).

  28. shell script portability depends on the unix tools by mataap · · Score: 1
    Where shell script portability falls down is often in the need to call external utilities. Once you move beyond a common set of basic functionalities, many unix tools will vary in their behaviour. E.g. find, make, tar, ps, even ls vary from platform to platform. Even if your script is written portably, you have to take account of the variance of the tools the script calls.

    I recall one script that broke because ls on one system put an extra leading space in its output. (I think it was an old sgi box.)

    Yes, there is posix. So if you must write scripts, try to stick to that. But I have some systems here that are pretty old, and I can't be sure that they are posix compliant.

    When I have to use unix tools, I try to arrange for the gnu utilities to be built and installed, so I only have to consider one set of man pages, and not a set for each platform the script has to run on. Similarly, makefile portability is difficult because make behaviour varies between platforms e.g. vpath, so I try to arrange for gnu make to be installed.

    In response to those people who just shell out from python: that's a method that I have seen a few times among programmers transitioning from shell to python scripting, including myself. You end up with a bash script where every line is wrapped with os.popen calls. No, the way to write a python script is to look in the library doco for the modules that have the functionality you want. As someone pointed out, find -> os.walk for example. Plus os.popen or os.subprocess from python is still vulnerable to the non-portability that results from behaviour variation of unix tools across platforms.

    My preference these days is to write scripts in python, but I agree that there will be systems without python, where shell is required. In those cases, it is great to know how write scripts with better portability, so the book in the post is likely a good addition to the library.

  29. env.d by sqldr · · Score: 1

    So a lot of scripts tend to make the same mistake. They set up the environment on the first line, then use that throughout the script. Another script using the same stuff will have to do the same thing.

    So you put this at the top of your script:

        FOO="path/to/some/stuff"

    And in lots of other scripts. WRONG!

    Create "/opt/yourcompany/etc/env.d/foo" and put it in there.

    Create "/opt/yourcompany/etc/profile" which executes env.d/*

    Put "source /opt/yourcompany/etc/profile" at the top of all your scripts.

    Wow.. now your scripts are relocatable!

    HTH HAND burp.

    --
    I wrote my first program at the age of six, and I still can't work out how this website works.
    1. Re:env.d by seebs · · Score: 1

      "source" is a cshism, which happens to be handled by bash. The portable shell spelling is ".".

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/