CSE 80 -- Lecture 6 -- Jan 23


Today I went over the xit and zap shell scripts that I put in the ../public directory. I created them this way:
$ cat > xit
#!/software/common/gnu/bin/bash
exit ${1:-0}
^D
$ chmod +x xit
and
$ cat > zap
#!/software/common/gnu/bin/bash
kill -${1:-15} $$
^D
$ chmod +x zap

The xit script takes an optional argument and will cause the interpreting shell to exit with the exit status specified by that argument; if the optional argument is missing, a default value of 0 is used.

Similarly, the zap script takes an optional argument and will cause the interpreting shell to be killed with that signal; if the optional argument is missing, a default value of 15 is used. This is SIGTERM, which is the default for kill.

C Bit Manipulation

This is a diversion into how to manipulate bits in integer variables in C, in case you need it to handle the result of the wait system call in assignment 2.

Given an integer variable i, the & binary operator is how you do bitwise AND: if i is 0110 1010 0011 1100 1001 1011 1111 0001 in binary (the Suns you're using are 32-bit machines), and you evaluated the expression i&0xff, the result is the low-order 8 bits of i. The hexidecimal constant 0xff is 1111 1111 in binary, so the AND of it and i would give 1111 0001 or 0xf1. Bits may be moved around using the operators. Right is >>, and i>>8 would be 0000 0000 0110 1010 0011 1100 1001 1011 in binary. The bits that "fell off the end" just disappears, and zeros are shifted in from the left (actually, the `sign bit' is replicated when the variable is signed, but you needn't worry about that.)

Argument parsing example

This is the somewhat cheesy argument parsing example. Instead of a better, more generic parsing template, I'm using a simpler structure due to the fact that this die script may only be invoked in two ways: die -x exit-status or die -k signum.
$ cat > die
#!/software/common/gnu/bin/bash
case $# in
2)	;;
*)	echo "I need two arguments!" >&2
	exit 1;;
esac
case $1 in
-x)	exit $2;;
-k)	kill -$2 $$;;
*)	echo "first arg must be either -x or -k" >&2
	eixt 1;;
esac
^D
$ chmod +x die

[ CSE 80 | ACS home | CSE home | CSE calendar | bsy's home page ]
picture of bsy

bsy@cse.ucsd.edu, last updated Tue Mar 18 15:49:28 PST 1997.

email bsy