在tcsh中出现异常行为。为什么这里的exit命令会被忽略?
这看起来像预期的行为吗?
[jlong1s@testlogin01 ~]$ ps
PID TTY TIME CMD
3602516 pts/3 00:00:00 tcsh
3603415 pts/3 00:00:00 ps
[jlong1s@testlogin01 ~]$ /usr/bin/tcsh -c 'if ( 1 ) then \
? echo in if construct \
? exit 1 \
? echo still in if construct . . . wow \
? endif \
? '
in if construct
still in if construct . . . wow
我不指望第二条echo命令会被执行。
如果我在命令行中尝试同样的一行代码,退出的结果是登出,正如预期。
[jlong1s@testlogin01 ~]$ if ( 1 ) then
[jlong1s@testlogin01 ~]$ echo in if construct
in if construct
[jlong1s@testlogin01 ~]$ exit
logout
解决方案
我觉得 \ 的反斜杠换行并没有达到你希望的效果。
无论如何,我不建议把它做成单行命令。
把多行的shell脚本放到一个文件中。
在macOS Tahoe 26.3上,我得到的结果完全符合预期。
% cat exit.csh
#! /bin/tcsh
echo ${version}
echo
if ( 1 ) then
echo in if construct
exit 1
echo still in if construct . . . wow
endif
%
% ./exit.csh
tcsh 6.21.00 (Astron) 2019-05-08 (unknown-apple-darwin) options wide,nls,dl,bye,al,kan,sm,rh,color,filec
in if construct
也就是说,我们没有看到后续的“wow”这句注释,因为进程按预期退出。
此外,正如Tom Christiansen advises 所建议的那样,最好在 bash 中编写多行shell脚本。
参见Bruce Barnett的相关 essay:
C shell(以及TCSH)最大的问题在于它的临时性解析器。 ...
C shell不会这样。它是在执行时就进行解析。
你可能会发现 while 与 if 一样让人头疼。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。