如何检查 tcsh 中的字符串是否为空?
在你吓坏之前,不,我不是在用 tcsh 编写 shell 脚本。我问是因为我想在我的 .tcshrc 文件中使用它。
具体来说,我想在 tcsh 中做这个 bash 代码的等价物:
if [[ -z $myVar ]]; then
echo "the string is blank"
fi
Run Code Online (Sandbox Code Playgroud)
if ("$myVar" == "") then
echo "the string is blank"
endif
Run Code Online (Sandbox Code Playgroud)
请注意,在 csh 中,尝试访问未定义的变量是错误的。(从 Bourne shell 的角度来看,它好像set -u一直有效。)要测试是否定义了变量,请使用$?myVar:
if (! $?myVar) then
echo "myVar is undefined"
else
if ("$myVar" == "") then
echo "myVar is empty"
else
echo "myVar is non-empty"
endif
endif
Run Code Online (Sandbox Code Playgroud)
请注意嵌套if. 你不能else if在这里使用,因为"$myVar" == ""即使第一个条件为真,这也会导致条件被解析。如果要以相同的方式处理空和未定义的情况,请先设置变量:
if (! $?myVar) then
set myVar=""
endif
if ("$myVar" == "") then
echo "myVar is empty or was undefined"
else
echo "myVar is non-empty"
endif
Run Code Online (Sandbox Code Playgroud)