[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Bash commands



Russell <rjshaw@iprimus.com.au> [2002-09-01 15:40:58 +1000]:
> I might have gotten somewhere initially if i hadn't have
> used those square [] brackets.

A couple of gratuitous comments concerning the scripting plus the
helpful comments which were posted.  I can't help but to say
something.  I know, I know, I need therapy.

1. Using `` is the same as $() except that the $() are prefered since
   you can nest them without needing to do crazy quoting.  The quoting
   in general inside of $() is slightly better.  All modern shells
   support $().  The old Bourne shell does not.

2. The 'if' executes a command.  The '[' is a command.  Therefore if
   you can use the return code of a command directly it is ever so
   slightly more efficient since you have one less command.

     if grep -q foo /path/to/file; then

   is better than

     if [ -n "$(grep foo /path/to/file)" ]; then

3. You can negate the return code easily using '!'.

     if ! grep -q foo /path/to/file; then

   is better than

     if [ -z "$(grep foo /path/to/file)" ]; then

4. When using test you should always quote your test case.  This
   following case is bad since if the grep does not produce something
   then you get a syntax error from test.  But if it does produce
   something then you don't.  Coding with data dependent failures is
   always to be avoided.

     if [ -n $(grep foo /path/to/file) ]; then  # poor syntax, unreliable

5. Different shells treat pipelines differently.  IIRC it used to be
   with the old Bourne shell the return code is the return code of the
   last command to exit and not the last command in the pipeline.
   Which can make for subtle errors that are hard to debug.  I don't
   know if this is a concern with modern shells but I have been
   avoiding those cases for ten years.

Bob

Attachment: pgp9UpZtoV1CI.pgp
Description: PGP signature


Reply to: