How to warn for the use of unset variables in a KornShell script.

Is there any way to throw errors or warnings in a KornShell (ksh) script to prevent the use of unset variables? Let's assume I have a temporary folder that I want to remove.

TEMP_FILES_DIR='/app/myapp/tmp'
rm -Rf $TEMP_FILE_DIR #notice the misspelling

How to prevent this kind of mistakes before they actually happen?

I know the script should check for file existence and empty string before attempting to remove, this is just a silly example to illustrate a mistake that could have been avoided with some warnings. I don't know if this feature exists in ksh. If it does exist, how do you turn it on?

Answers


The command

set -u

Will cause POSIX sh(1) and its derivatives to grouse when an attempt to expand an unset variable is made.

Example:

$ echo $foo

$ set -u
$ echo $foo
sh: foo: parameter not set

You could check the variable for having content, ie not being '', and print-out a message like "the variable is empty".

However, that's still not going to fix PEBCAK errors like this - all you'd know is that nothing happened.


Need Your Help

Static vs global in terms of speed and space consumption in C

c gcc static embedded global

I would like to know difference between static variables and global variables in terms of access speed and space consumption. (If you want to know my platform: gcc compiler on Windows. (I am using ...

Meteor Cordova input field white band above soft keyboard

android cordova meteor user-accounts meteoric

I am using ionic sign in and sign up screens from http://useraccounts.meteor.com/