Shell脚本生成SQL INSERT语句缺失引号问题求助
Shell脚本生成SQL INSERT语句缺失单引号问题解决
问题说明
需求是读取文件中的数字,生成符合以下格式的SQL INSERT命令:
INSERT INTO `opensips`.`usr_preferences`(`uuid`, `username`, `domain`, `attribute`, `type`, `value`, `last_modified`) VALUES ('1111111111', '1111111111', 'mydomain.com', 'fs', 2, '8.8.8.8', NOW());
但实际生成的语句中,字符串类型的字段(uuid、username、domain、attribute、value)都缺失了单引号,结果如下:
INSERT INTO `opensips`.`usr_preferences`(`uuid`, `username`, `domain`, `attribute`, `type`, `value`, `last_modified`) VALUES (1111111111, 1111111111, mydomian.com, fs, 2, 8.8.8.8, NOW());
原脚本代码:
echo "Removing Carriage" #Remove carriage from file sed 's/\r$//' update.txt > forprocessing.txt sleep 1 echo "Generating Output" sleep 2 #Generate Output echo "" file="forprocessing.txt" while IFS= read line do #Add new routing rule echo 'INSERT INTO `opensips`.`usr_preferences`(`uuid`, `username`, `domain`, `attribute`, `type`, `value`, `last_modified`'') VALUES ('$line', '$line', ''mydomian.com', 'fs', 2, '8.8.8.8',' NOW());' done <"$file" echo "" echo "========" echo "Finished" echo "========" #Clean up rm forprocessing.txt
解决方法
问题出在echo语句的引号处理上:原脚本用单引号包裹整个字符串,导致内部单引号无法正确输出,且变量解析逻辑混乱。修改后的脚本如下:
echo "Removing Carriage" # Remove carriage from file sed 's/\r$//' update.txt > forprocessing.txt sleep 1 echo "Generating Output" sleep 2 # Generate Output echo "" file="forprocessing.txt" while IFS= read line do # Add new routing rule echo "INSERT INTO `opensips`.`usr_preferences`(`uuid`, `username`, `domain`, `attribute`, `type`, `value`, `last_modified`) VALUES ('$line', '$line', 'mydomain.com', 'fs', 2, '8.8.8.8', NOW());" done <"$file" echo "" echo "========" echo "Finished" echo "========" # Clean up rm forprocessing.txt
关键修改点
- 引号调整:将
echo的外层单引号改为双引号,这样可以正常解析变量$line,同时直接在需要单引号的字段前后添加单引号(如'$line'会输出为'1111111111')。 - 修正语法错误:删除了原脚本中
last_modified后的多余单引号,修正为正确的)。 - 拼写修正:将域名
mydomian.com改为正确的mydomain.com。
内容的提问来源于stack exchange,提问作者gareth0402
相关产品推荐
相关产品推荐

