目标
shell中根据指定分隔符将字符串拆分成数组,然后遍历该数组
知识点
shell中的$IFS
Shell 脚本中有个变量叫IFS(Internal Field Seprator) ,内部域分隔符。
完整定义是:
The shell uses the value stored in IFS, which is the space, tab, and newline characters by default, to delimit words for the read and set commands, when parsing output from command substitution, and when performing variable substitution.
Shell 的环境变量分为set, env 两种,其中 set 变量可以通过 export 工具导入到 env 变量中。其中,set 是显示设置shell变量,仅在本 shell 中有效;env 是显示设置用户环境变量 ,仅在当前会话中有效。换句话说,set 变量里包含了env 变量,但set变量不一定都是env 变量。这两种变量不同之处在于变量的作用域不同。显然,env 变量的作用域要大些,它可以在 subshell 中使用。
IFS 是一种 set 变量,当 shell 处理”命令替换”和”参数替换”时,shell 根据 IFS 的值,默认是 space, tab, newline 来拆解读入的变量,然后对特殊字符进行处理,最后重新组合赋值给该变量。
$IFS的使用
查看$IFS的值
echo “$IFS”
不会显示任何内容
echo “$IFS”|od -b
展示内

本文介绍如何在Shell脚本中使用IFS变量根据指定分隔符将字符串拆分成数组,并遍历处理这些元素。文章详细解释了IFS的含义及应用场景。
最低0.47元/天 解锁文章
2682

被折叠的 条评论
为什么被折叠?



