dialog命令--checklist输出无引号,如何确保输出被正确引用?
问题:dialog checklist未按预期输出带引号的选项值
原脚本
#!/bin/bash # Save response to this file respFile=$1 dialog --backtitle "Test" \ --checklist "Observe the following expected conditions and \ confirm the actual results were detected by placing \ an X in any of the boxes.\n\n\nLeave the box blank if the actual result does not match the expected. \ \n\n Space bar toggles the X.\n Cursor selects a row.\n" \ 25 60 6 \ 1 "Condition A" off \ 2 "Condition B" off \ 3 "Condition C" off \ 2> ${respFile} # Ensure file is not zero length. echo $0 >>${respFile} echo $0 complete >> ${respFile}
预期与实际输出差异
选中1、2、3三个选项后,预期respFile内容:
"1" "2" "3" file.sh file.sh complete
实际得到的内容:
1 2 3 file.sh file.sh complete
已尝试的无效方法
给选项值直接加引号:
"1" "Condition A" off \ "2" "Condition B" off \ "3" "Condition C" off \→ 引号被bash解析忽略,输出仍为无引号的
1 2 3 ...转义引号强制传入:
'"1"' "Condition A" off \ '"2"' "Condition B" off \ '"3"' "Condition C" off \→ 输出出现冗余转义引号:
"\"1\"" "\"2\"" "\"3\"" file.sh file.sh complete
问题背景
根据dialog文档描述,未使用--separate-output选项时,输出字符串应自动被引号包裹,但实际未生效。
解决方案
该问题多由dialog版本/发行版打包差异导致,部分新版dialog默认取消了自动加引号的行为,可通过以下方式手动处理:
方法1:实时处理dialog输出
修改dialog的重定向逻辑,用sed给输出内容添加引号:
dialog --backtitle "Test" \ --checklist "Observe the following expected conditions and \ confirm the actual results were detected by placing \ an X in any of the boxes.\n\n\nLeave the box blank if the actual result does not match the expected. \ \n\n Space bar toggles the X.\n Cursor selects a row.\n" \ 25 60 6 \ 1 "Condition A" off \ 2 "Condition B" off \ 3 "Condition C" off \ 2> >(sed 's/\b\([0-9]\)\b/"\1"/g' > ${respFile})
方法2:事后修改结果文件
在dialog执行完成后,对结果文件的第一行内容批量添加引号:
# 原dialog命令保持不变 dialog [...] 2> ${respFile} # 添加引号处理逻辑 sed -i '1s/\([0-9]\)/"\1"/g' ${respFile}
补充说明
可执行dialog --version查看当前版本,部分新版dialog需参考对应文档,使用--output-separator等选项配合自定义输出格式。
内容的提问来源于stack exchange,提问作者will
相关产品推荐
相关产品推荐

