如何警告在KornShell脚本中使用未设置的变量。

时间:2021-04-15 00:37:24

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.

有没有办法在KornShell(ksh)脚本中抛出错误或警告,以防止使用未设置的变量?假设我有一个我想删除的临时文件夹。

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?

我知道脚本应该在尝试删除之前检查文件是否存在和空字符串,这只是一个愚蠢的例子来说明一些警告可以避免的错误。我不知道ksh中是否存在此功能。如果它确实存在,你如何打开它?

2 个解决方案

#1


6  

The command

set -u

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

当尝试扩展未设置的变量时,将导致POSIX sh(1)及其衍生物发挥作用。

Example:

$ echo $foo

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

#2


0  

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.

然而,这仍然不会像这样修复PEBCAK错误 - 所有你知道的是没有发生任何事情。

#1


6  

The command

set -u

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

当尝试扩展未设置的变量时,将导致POSIX sh(1)及其衍生物发挥作用。

Example:

$ echo $foo

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

#2


0  

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.

然而,这仍然不会像这样修复PEBCAK错误 - 所有你知道的是没有发生任何事情。