Bash脚本输出异常:输入内容未正确匹配对应字段求助
Bash脚本字段分配错误问题分析与解决
问题场景
现有一段用于读取input.txt内容并格式化输出的Bash脚本,运行后字段分配不符合预期,无法得到目标输出结果。
原脚本
#!/bin/bash read -p "Enter an apartment number:" aptNumber while IFS=$' \n' read -r firstName lastName leaseStart leaseEnd balance; do echo "Apartment Number: $aptNumber" echo "Tenant Name: $lastName,$firstName" echo "Lease Start: $leaseStart" echo "Lease End: $leaseEnd" echo "Current Balance: $balance" done < input.txt
input.txt内容
John Doe 07/07/19 07/07/20 900
当前错误输出
Enter an apartment number:001 Apartment Number: 001 Tenant Name: Doe,John Lease Start: Lease End: Current Balance: Apartment Number: 001 Tenant Name: 07/07/20,07/07/19 Lease Start: Lease End: Current Balance: Apartment Number: 001 Tenant Name: ,900 Lease Start: Lease End: Current Balance:
期望输出
Apartment Number: 001 Tenant Name: Doe,John Lease Start: 07/07/19 Lease End: 07/07/20 Current Balance: 900
错误原因
- 逐行读取逻辑错误:原脚本的
while循环会逐行读取input.txt内容,文件共3行,循环执行3次。每次仅处理一行的字段,无法一次性获取所有需要的5个字段,导致除前两个变量外,其余变量均为空。 - IFS设置未改变逐行读取行为:虽然设置了
IFS=$' \n',但read命令默认仍以换行符作为输入行的分隔符,每行内按空格分割字段,无法跨行合并内容填充所有变量。
修正方案
方案一:分三次读取文件行
通过文件描述符打开文件,分三次读取每行内容,分别匹配对应变量:
#!/bin/bash read -p "Enter an apartment number:" aptNumber # 打开文件描述符3关联input.txt 3< input.txt # 读取第一行姓名 read -r firstName lastName <&3 # 读取第二行租赁日期 read -r leaseStart leaseEnd <&3 # 读取第三行余额 read -r balance <&3 # 关闭文件描述符 exec 3<&- echo "Apartment Number: $aptNumber" echo "Tenant Name: $lastName,$firstName" echo "Lease Start: $leaseStart" echo "Lease End: $leaseEnd" echo "Current Balance: $balance"
方案二:一次性合并读取所有内容
将文件内容合并为单行后,一次性分配给所有变量:
#!/bin/bash read -p "Enter an apartment number:" aptNumber # 合并文件所有内容为单行,按空格分割分配变量 read -r firstName lastName leaseStart leaseEnd balance <<< "$(cat input.txt)" echo "Apartment Number: $aptNumber" echo "Tenant Name: $lastName,$firstName" echo "Lease Start: $leaseStart" echo "Lease End: $leaseEnd" echo "Current Balance: $balance"
修正说明
- 方案一通过独立文件描述符控制读取,精准对应文件的每行内容,避免循环重复输出,同时保证每行内的字段正确分配。
- 方案二利用
$(cat input.txt)将文件的换行符转换为空格,把所有内容合并为一个包含5个字段的输入行,通过一次read命令完成所有变量的分配,逻辑更简洁。
内容的提问来源于stack exchange,提问作者Reid Boulet
相关产品推荐
相关产品推荐

