Solaris 10下while循环后变量def值未保留问题求助
问题原因
Solaris 10自带的sh是传统Bourne shell,当使用while read结合here-doc重定向时,循环会在子shell中运行。子shell拥有独立的变量环境,循环内对def的修改仅在子shell生效,子shell结束后父shell的def变量不会被更新,因此循环外输出为空。
解决方案
方案1:用命令替换捕获循环输出
将循环中需要拼接的内容逐行输出,通过命令替换捕获所有输出(自动将换行转为空格),直接赋值给def:
#!/usr/bin/sh def=$(while read x; do echo "-D$x" done <<-COMMANDS_GREEN hello="hello green world" host="greenmen.com" port=80 COMMANDS_GREEN) echo definition: $def
方案2:使用文件描述符重定向避免子shell
通过自定义文件描述符读取here-doc内容,让while循环在当前shell进程中执行,变量修改会保留:
#!/usr/bin/sh def="" # 将here-doc内容绑定到文件描述符3 exec 3<<-COMMANDS_GREEN hello="hello green world" host="greenmen.com" port=80 COMMANDS_GREEN # 从文件描述符3读取内容,循环在当前shell执行 while read x <&3; do def="$def -D$x" echo $def done # 关闭文件描述符3 exec 3<&- echo definition: $def
验证效果
两种方案运行后,都会输出:
definition: -Dhello="hello green world" -Dhost="greenmen.com" -Dport=80
内容的提问来源于stack exchange,提问作者armagedescu
相关产品推荐
相关产品推荐

