[ale] Bash confusion

Brian MacLeod nym.bnm at gmail.com
Wed Jul 20 13:04:10 EDT 2011


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 7/20/11 11:41 AM, Robert L. Harris wrote:
> 
> 
> Ok, simple one...  I have a script that has this:
> 
> 
> #!/bin/bash
> 
> date=`date +%d` if [ $date = "01" ]; then # Run Monthly Backup else #
> Run Incremental Backup fi
> 
> From the man page of 'date': %d     day of month (e.g, 01)
> 


You are doing a string comparison here, so you should take the correct
precautions:

> if [ $date = "01" ];

should be like this:

if [ "01" = "$date" ];

Why?

If for some ungodly reason your variable ends up as null, the whole
statement (and function, etc) breaks if you have that null in front of
the equal sign.  Flip that around and it "properly" evaluates even if
null. Otherwise you'll see things like "unary operator" and such.

The other thing is making sure you treat your variable as a string,
thus, quote it so that you are sure it isn't being further evaluated
and/or evaluated differently.

Some even say you should curly bracket the name (ie: ${date}), but in
this simple case it is overkill.  Only if you were making a compound
string would I worry too much about that. But if you get used to doing
it with curlies, than you won't pull your hair out on more complex
manipulations.

And, finally, are you sure you don't have something else running or
setting up environment variables?  Date is a common one, and in this
case, I normally use $DOM (day of month) to make sure I don't clobber or
evaluate the wrong thing.


Brian

-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.14 (Darwin)

iQEcBAEBAgAGBQJOJwqJAAoJEPlcIlj+rhjoNSAH/3G8O7oc3cdtS+WAUcVpZKKy
i9RdaDk2o0jT2mLPz3kXhMEczc2ekQdTTo7EYV+Rm7JHj1D37LnwTy+DykbXKnBn
1J4DUA13wUCfmVJi2K588Rb43zMF3xdI8s6A+oIGfE+k+r1nNdJ6vZ4EiHQxzBni
cg0C2nCVxQwZdmQK4bK+g33LreE1SyalNtT0bsRzEl1AFPHn08SxHlPF8enBumvW
gtoG1FCBfITrOKfW4+0ZJlcEo8HkqVBwxjRw4Uk5CUKqAkDlX0TwRmXjiWOK/MtQ
61aqhg94deUqAKo9FXDU3qp+HboId0bWFDzSy/SWb1ykKPaEoTGbGctc7vjPB4g=
=kFi7
-----END PGP SIGNATURE-----


More information about the Ale mailing list