C Shell报错if: Expression Syntax,if语句语法异常问题排查求助
C Shell 「if: Expression Syntax」报错解决方案
核心报错原因
C Shell的表达式解析规则要求:字符串比较时如果变量可能包含空格、特殊字符或为空,必须用双引号包裹变量,否则变量展开后会打乱if表达式的结构,直接触发语法错误。
修复方案
你只需要修改if语句的变量写法,将$curr_line用双引号包裹即可解决报错:
#!/bin/csh -f foreach line("`cat file.txt`") set curr_line = `echo $line | awk '{print substr($0, 1, 20)}'` # 变量包裹双引号修复语法错误 if ("$curr_line" == "string of text...") then echo "Success!" endif end
额外优化建议
- 你当前的
foreach写法会按空白符(空格、换行、制表符)分割内容,而非按行分割,如果你需要严格逐行读取文件,建议使用while循环实现:
#!/bin/csh -f set target_file = "file.txt" set line_count = `wc -l < $target_file` set idx = 1 while ($idx <= $line_count) set line = `sed -n "${idx}p" $target_file` set curr_line = `echo $line | awk '{print substr($0, 1, 20)}'` if ("$curr_line" == "string of text...") then echo "Success!" endif @ idx += 1 end
内容的提问来源于stack exchange,提问作者Ghengis Sean
相关产品推荐
相关产品推荐

