Based on the algorithm in Wikipedia, this script takes a four-digit year as an argument, and determines whether or not it is a leap year. Obviously not super-useful in itself, the "if" line could be incorporated into a larger script. Appears to work in ksh and bash, but not sh.
year=$1
if [ $((year%400)) -eq 0 ] || \
( [ $((year%4)) -eq 0 ] && [ $((year%100)) -ne 0 ] )
then
echo "leap"
else
echo "not leap"
fi
Monday, April 19, 2010
Tuesday, April 6, 2010
Dynamic korn shell (ksh) variable assignments
This might seem like a strange thing to want to do, but imagine you read in a list of user names, and for each one you want to store some info, such as the assigned shell.
Now, you could just put user names in one array, and the info in another array, and rely on the fact that both arrays will have the same index order.
But, you can also use "eval":
$ name=bob
$ data=/bin/bash
$ eval "$name=$data"
And to "de-reference" your dynamic variable:
$ eval "echo \$$name"
/bin/bash
This also works:
$ eval echo "$"$name
/bin/bash
Now, you could just put user names in one array, and the info in another array, and rely on the fact that both arrays will have the same index order.
But, you can also use "eval":
$ name=bob
$ data=/bin/bash
$ eval "$name=$data"
And to "de-reference" your dynamic variable:
$ eval "echo \$$name"
/bin/bash
This also works:
$ eval echo "$"$name
/bin/bash
Subscribe to:
Posts (Atom)