OT: bash help

Ian Malone ibmalone at gmail.com
Sun Aug 17 12:38:28 UTC 2014


On 17 August 2014 08:36, Cameron Simpson <cs at zip.com.au> wrote:
> On 16Aug2014 14:44, Mike Wright <mike.wright at mailinator.com> wrote:
>>
>> I'm trying to write a simple script that if provided an argument, uses
>> that, or if nothing is provided, uses a predefined string.
>
>
> This is general shell stuff, not bash specific.
>
>> if [ -n $# ]
>
>
> This is always true. Even "0" is a nonempty string.
>
> Test [ $# -gt 0 ] instead.
>
>

Though it's a matter of preference I'd prefer [ $# = 0 ] or  [ $# != 0
] tests unless you really need one of the numeric comparisons. The
reason (and it doesn't actually apply for $#, hence matter of
preference) is that if you have somehow ended up with a string rather
than a number (e.g. an error from wc or something) then you have to
think about what your comparison is going to do for that case, whereas
the =! and == comparisons will do what you expect. If you do need -gt,
-lt and the rest then (except for $#) it's best to check what you've
got is a number first.


-- 
imalone
http://ibmalone.blogspot.co.uk


More information about the users mailing list