Shell already does it for you.
In Bourne shell the result of the last executed command is saved in variable $?
In C shell it's a built-in variable called status.
Here's the sample script:
- #!/bin/sh
-
[ -d `pwd` ]
-
echo $?
-
# the statement above should print 0, (success status)
-
# because your current directory is obviously a directory.
-
-
[ -d /dev/nonsence ]
-
echo $?
-
# the statement above will likely to print 1 (failure),
-
# it's unlikely that this directory exists
Note that 0 is always a success, but shell may return other failure codes,
so most often you're only interested to see whether you gor 0 or not:
exec some shell command, then test the result:
if [ "$?" -ne 0 ] ; then
... ...
It is a common practice to include $? in double-quotes, as shown above.
Hope it helps.