Shell脚本语法错误求助:仅当文本文件存在时生成JSON文件
修正后的Shell脚本及错误解析
修正后的代码
File="ABC.txt" if [ -f "$File" ]; then echo "file exist" json_data=$(cat <<EOF { "Data_format": "txt", "Dataset_name": "abc.txt", "No_of_file": "1", "Header": true, "delimeter": ",", "Code_page": "UTF-8" } EOF ) echo "$json_data" echo "$json_data" > incident.json else echo "Text file doesn't exist" fi
原脚本的错误点解析
- 变量赋值错误:Shell中变量赋值时
=两边不能有空格,原脚本File = " ABC.txt"会被解析为命令File,导致语法错误;同时文件名前的多余空格会导致文件存在性判断失效,需改为File="ABC.txt"。 - 关键字大小写错误:Shell的条件关键字
if、else必须小写,原脚本的If、Else会被识别为普通命令,引发语法错误。 - 条件判断的空格问题:
[是Shell的内置命令,前后必须加空格;变量$File需用双引号包裹("$File"),防止文件名含空格时判断失效;原脚本[ -f $File];应改为[ -f "$File" ];。 - JSON语法错误:
"Header" :true后缺少逗号,会导致JSON格式无效;"Code_page": "UTF-8",末尾的多余逗号也要删除,修正为"Header": true,和"Code_page": "UTF-8"。 - Here Document格式错误:
<<EOF对应的结束标记EOF必须顶格书写(不能有缩进),原脚本的EOF前有空格,导致Shell无法识别结束标记,从而抛出Unexpected EOF while looking for matching ') '错误。 - 输出语句缺失:
else块中的"Text file doesn't exist"没有echo命令,无法输出提示信息,需改为echo "Text file doesn't exist"。
内容的提问来源于stack exchange,提问作者Pooja kumari
相关产品推荐
相关产品推荐

