Thursday, January 27, 2011

Shell Variables are Global by Default

All variables in a shell script are global unless specifically declared as local. Local variables can be used only inside a function.

#!/bin/bash
# Global and local variables

carwash()
{
local vin="17DIGITS"
echo "IN Carwash. Your windscreen is:" $1 "and your VIN is:" $vin
post_carwash_status="BEARY CLEAN"
}

status="DIRTY"
carwash $status
echo "After carwash. Your windscreen is:" $status "and your VIN: " $vin
echo "Post Carwash Status: " $post_carwash_status

OUTPUT

IN Carwash. Your windscreen is: DIRTY and your VIN is: 17DIGITS
After carwash. Your windscreen is: DIRTY and your VIN: 
Post Carwash Status:  BEARY CLEAN
Notice that the local variable vin is not available outside the function.

No comments:

Post a Comment