[TriLUG] String Evaluation

Marty Ferguson marty.ferguson at pobox.com
Wed Jul 30 15:59:48 EDT 2008


They function the same as long as the string variable teststring is defined.
The results will differ when teststring is undefined, which makes cases 
2 and 3 more advantageous as a shell script construct.

If teststring is not defined, then, because $teststring evaluates to 
null,  the shell will compose  the case 1 test expression as:

if [ -n ]; then ...

I.e., no argument presented to the test statement.

Whereas in cases 2 and 3, the evaluation will essentially be

if [ -n  "" ]; then ...

and a null string will be presented to the test statement as an argument.

Marty

========
Craig Taylor wrote:
> They function the same - however using ${myvar} allows you to do stuff
> comparisons against strings such as "${myVar}suffix" - whereas
> "$myVarsuffix" would obviously fail.
>
>
> On Tue, Jul 29, 2008 at 1:16 PM, Shawn Taylor <shtaylor at gpi.com> wrote:
>
>   
>> Can someone please explain the difference between these variable usages?
>>
>> Specifically is it better/more common/more portable to use ${testString}
>> instead of "$testString" in my scripts?
>>
>> Example below.
>>
>> Thanks,
>>
>> Shawn
>>
>> <script>
>>
>> #!/bin/bash
>>
>> declare testString
>> testString="This is a test string"
>>
>> echo $testString
>> echo "$testString"
>> echo ${testString}
>>
>> # THIS IS WHERE THE FUN BEGINS
>>
>> if [ -n $testString ]; then
>>        echo "String Not Empty - 1"
>> fi
>>
>>
>> if [ -n ${testString} ]; then
>>        echo "String Not Empty - 2"
>> fi
>>
>>
>> if [ -n "$testString" ]; then
>>        echo "String Not Empty - 3"
>> fi
>>
>> </script>
>>
>>
>>
>> --
>> TriLUG mailing list        : http://www.trilug.org/mailman/listinfo/trilug
>> TriLUG FAQ  : http://www.trilug.org/wiki/Frequently_Asked_Questions
>>
>>     




More information about the TriLUG mailing list