Slashdot Mirror


How To Adopt 10 'Good' Unix Habits

An anonymous reader writes to mention an article at the IBM site from earlier this week, which purports to offer good Unix 'habits' to learn. The ten simple suggestions may be common sense to the seasoned admin, but users with less experience may find some helpful hints here. From the article: "Quote variables with caution - Always be careful with shell expansion and variable names. It is generally a good idea to enclose variable calls in double quotation marks, unless you have a good reason not to. Similarly, if you are directly following a variable name with alphanumeric text, be sure also to enclose the variable name in square brackets ([]) to distinguish it from the surrounding text. Otherwise, the shell interprets the trailing text as part of your variable name -- and most likely returns a null value."

16 of 360 comments (clear)

  1. FP? by Shadow-isoHunt · · Score: 5, Funny

    export POST="first"

    --
    www.isoHunt.com
  2. welll.. by macadamia_harold · · Score: 5, Funny

    An anonymous reader writes to mention an article at the IBM site from earlier this week, which purports to offer good Unix 'habits' to learn.

    I seriously doubt reading this article is going to get anyone to start showering on a regular basis.

    1. Re:welll.. by AchiIIe · · Score: 5, Insightful

      Some of the points he is making are BS. They are not good `Unix habits` they are simply hacks that marginally reduce the workload but (arguably) increase complexity.

      Ie there is NOTHING bad about piping cats. While you might indeed get a ~30% performance increase if you skip the cat, the complexity increases. We often sacrifice performance in order to increase abstraction and understanding.

      What makes unix so powerful is its modularity, the fact that you can pipe any output from any application to any applications stdin. This makes it possible to use common tools app1 | app2, app1longoutput | grep thingsIwant. The possibility to mix and match common elements that (arguably) makes unix powerful.

      Advice that says "stop piping cats" is akin to "stop using helper functions, they overload the stack, instead do everything in one function"

      --
      A better articulated article on the programmers intellectual ability vs proper abstraction techniques:
      http://www.acm.org/classics/oct95/ - Dijkstra, Edsger - "Go To Statement Considered Harmful"

      --
      Nature journal lied in Britannica vs Wikipedia Ask to retrac
    2. Re:welll.. by SharpFang · · Score: 5, Funny

      Ie there is NOTHING bad about piping cats

      PETA would disagree.

      --
      45 5F E1 04 22 CA 29 C4 93 3F 95 05 2B 79 2A B2
    3. Re:welll.. by johnw · · Score: 5, Insightful

      I argue that using> grep file1 file2 file3 regex can be more confusing Not least to the grep utility, which expects the regex first, not last.

    4. Re:welll.. by Znork · · Score: 5, Insightful

      I'd tend to agree with the GP. Consider for example if you have excessively badly named files like '-whatever' in a particular directory; cat has very few destructive ways it can go wrong, other commands may be less forgiving, and cause much more surprise.

      Further, the assembly line abstraction of cat as 'input the contents of these files into the beginning of my pipeline' is predictable, simple and very clear and readable. Using the filenames in the commands means you have to be certain each command will take filenames, and if you replace the first step (from a grep to an awk, for example), you have to rethink your input method semantics again.

      Any typing speed gains and performance improvements you may get will probably get shot the first time some command does something unexpected, or by the extra steps of thought.

      And if performance really was a serious concern you probably shouldnt be writing it as a shell script...

    5. Re:welll.. by hackstraw · · Score: 5, Informative

      cat-ing a file and then piping it to grep. surely that is a good point he is making, because grep already takes filenames as an argument?

      That list was fairly arbitrary, but the piping cat thing is something that basically only annoys the most anal of anal, and they probably do it sometimes too.

      Its common for me to do cat foo and then hit the up arrow and append a pipe to another command instead of editing the whole command line. Computers are pretty fast, and real anal people would use fgrep instead of grep, but again I always use egrep, because I never know when a regular expression will be edited into a more complex one, and to me all of the speeds are the same.

      My #1 habit to tell people, although it is not a habit, but just where to start it to learn your shell. No science guys, csh is not a worthy shell in 2006. If you have to suffer with the wacky behavior of a csh variant, at least use tcsh.

      My #2 thing to learn is a text editor.

      As far as habits go. First and foremost, unalias cp, mv, rm to have the -i flag. In my opinion, that is a BAD habit to start. You WILL lose files sooner or later, and the more painful the better so that you will think so you will stop doing it. the -i flag will NOT stop you from redirecting into a file, and the most dangerous is the -rf flag with rm will override that -i. Remote copies via rcp or scp will not honor the -i flag. Unarchiving an archive will not honor the -i flag. There are tons of ways to lose files, and you will lose them. Its a much better habit to universally save yourself from yourself to not lose them by testing with -i, working off of a copy, and thinking before you hit return, creating new directories to eliminate clobbering a file, NEVER, EVER, do tar cf foo.tar . or tar cf foo.tar *. You will piss yourself and others by doing that.

      Actually, this top 10 list is pretty lame, and should be ignored.

  3. This article... by nevali · · Score: 5, Informative

    ...is so littered with basic errors that it really shouldn't be recommended to anybody. How is 'tar xvf -C tmp/a/b/c newarc.tar.gz' expected to work, for example? Quote variables with square brackets? Running subshell commands using ; instead of && ? No mention of 'xargs -0' ? Don't pipe from cat to grep? Does anybody actually care that people do this (primarily so that the syntax is consistent between a munged- and unmunged-grep, and also such that the order of the command-line is logical from a human point of view)? Plus, of course, it's possible that cat | grep could yield better performance than grep alone: if cat uses mmap() to efficiently read the input files, and the kernel's pipe implementation is good, then it could do better than a grep implementation alone that simply read()s the files.

  4. Re:Don't use shell by Anonymous Coward · · Score: 5, Insightful

    OK, I agree. Please provide a concise Python script that unpacks a tarball (a .tar.gz or .tar.bz2 file), copies new files in to a said tarball, patches based on the contents of said new files, runs make from various directories in said extracted tarball, and then changes the name of the top-level directory created by the tarball to a new name and repacks the tarball.

    Or a concise Python script that opens up a text file of URLs, and extracts the files listed in the URLs:

    #!/bin/sh
    for a in $( cat file | awk '{print "'\''" $0 "'\''"}' ) ; do
                  wget $a
    done


    Python has it place, and is far better for medium to large projects, and projects where the code needs to be maintainable. Shell, however, works a lot better for automating UNIX tasks than Python does. Not to mention embedded systems: I can compile Busybox to have both a good shell and all of the commands that one would run from shell scripts (including grep, cut, sed, and, yes, awk) in only about 300k. A Python binary is about a megabyte big, and you need about ten megabytes to fit all of the libraries Python 2.4 comes with.

  5. Very helpful by EvanED · · Score: 5, Funny
    I really like this example:

    ~ $ time grep and tmp/a/longfile.txt | wc -l
    2811

    real 0m0.097s
    user 0m0.006s
    sys 0m0.032s
    ~ $ time grep -c and tmp/a/longfile.txt
    2811

    real 0m0.013s
    user 0m0.006s
    sys 0m0.005s


    I am so glad that he showed what a difference can make, because I was *really* getting annoyed at having to wait that extra .084 seconds.
  6. Re:Don't use shell by Bazman · · Score: 5, Funny

    If I've got a simple task to do (eg the text-file-of-URLS example) then I knock it up in shell script. By the time that simple task has feature-creeped up to more than 20 lines I start to wish I'd written it in Perl. So I rewrite. By the time that Perl script has crept up to more than 200 lines I start to wish it was written in Python. So I rewrite. By the time that Python script has crept up to 2000 lines I start to wish I'd farmed the job out to a team of programmers, and I give up caring what language its written in and make them do it as a web service. Then I write a small shell script to call their web service. When that shell script has feature-creeped up to more than 20 lines...

  7. Things I had to learn the hard way by gd23ka · · Score: 5, Interesting

    1. Don't rm with an absolute path because you could easily

    #rm -r -f / tmp/dir

    when "all" you wanted was

    #rm -r -f /tmp/dir

    instead do this:

    #(cd /tmp ; rm -r -f dir)

    or even better use sudo if you have it:

    $(cd /tmp ; sudo rm -r -f dir)

    2. When logged on as root or when using sudo on a production system think things over
    at least twice before hitting enter.

    3. Make sure at all times you're on the right machine, logged on as the right user in the right directory.
    Set up your shell prompt to look like this user@host /path$

  8. Re:Square or Curly brackets? by lmfr · · Score: 5, Informative
    The correct form is {}, not []. There are other things you can use with ${VAR}:
    • ${VAR:-text if $VAR is empty}
    • ${VAR:=text if $VAR is empty and set VAR to this}
    • ${VAR:+text if $VAR is set}
    • ${#VAR} -> length of $VAR
    • ${VAR#pattern} or ${VAR##pattern} -> remove match of pattern from beginning of $VAR (## -> longest match)
    • ${VAR%pattern} or ${VAR%%pattern} -> remove match of pattern from end of $VAR (%% -> longest match)
    There are other formats (see the man page), but these are the ones I use the most. Eg:

    for i in *.png; do convert "$i" "${i%.*}.jpg"; done
  9. Actually useful hints by Artraze · · Score: 5, Informative

    As has been pointed out, this article is riddled with errors. It's also not very interesting. So in the interest of perhaps actually providing some interesting tips:

    In scripts, prefix dangersous commands with an 'echo' for a test run (So you can catch all those rm -rf /).

    Single quotes are the best quotes for plain strings. The only reasion to use double quotes is if you need to quote a variable or a single quote.

    Completion is fun, but using wildcards is more flexible (though you'll only want to use benign commans like cd, less, etc):
        nano /etc/modules.autoload.d/kernel-2.6
        nano /etc/m*a*d/*6

    Note that the use of subpaths reduces the amount of flexibility.
        cd /etc/m* -> /etc/mail
        cd /etc/m*d -> /etc/modules.d
        nano /*/m*/*6 -> /etc/modules.autoload.d/kernel-2.6, and /etc/modules.d/i386 (not quite!)

    Finally, as a comment for the article, using:
        test -e $DIR || mkdir -p $DIR
    is much better than their suggestion and probaly faster anyway. Though I'd just do "mkdir -p $DIR" and maybe "&>/dev/null" under most circumstances anyway.

    That's all I can think of at this point. Anyone else have tips?

  10. No actual habits in the article by xyloplax · · Score: 5, Insightful
    Here are some more important general IT rules (Unix rules can easily be OS and version dependent and frequently come from usage in YOUR environment)
    • Copy before edit
    • Tape backup before delete/decommission
    • READ YOUR COMMAND before hitting return
    • Check where things are symlinked to
    • Echo in your scripts instead of destructive commands as a test run
    • Test your changes on a lesser-importance box
    • Use proper Change Control procedures
    • Cover your ass and capture your terminal output
    • When taking something out of service, turn it off for a few days/weeks before deleting/purging it
    --
    -- "You can lead a yak to water, but you can't teach an old dog to make a silk purse out of a pig in a poke" - Opus
  11. Re:Don't use shell by JohnFluxx · · Score: 5, Insightful

    Wow, do you think you could be just a little bit more polite next time?