Shell中的 IFS

1、IFS 介绍shell

     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.bash

    当 shell 处理"命令替换"和"参数替换"时,shell 根据 IFS 的值,默认是 space, tab, newline 来拆解读入的变量,而后对特殊字符进行处理,最后从新组合赋值给该变量。
ide

    对于IFS的使用,惟一的途径,就是了解shell的执行顺序。在《shell脚本学习指南》第7章,179页,有个图,说的很清晰明了。在命令行上,对单引号字符串、双引号字符串、不带引号字符串的引用如何处理都讲的很清晰,以及IFS分隔字符串的时机。
整体上记住一点,双引号和单引号字符串引用能够屏蔽对命令参数使用IFS分割学习

wKiom1P19HziCeSLAAJeUKSJVl0900.jpg

    如上图所示,shell命令被解析执行的顺序。在第①步和第⑨步,都会进行一个 split 操做。在第①步中,咱们在命令行上输入命令,而后shell首先会把它们以IFS做为分隔符split为token, 而后到了第⑨步中,参数扩展和命令替换后的结果也会被以IFS为分隔符,split为word。ui

    如下是值得注意的地方:
spa

  1. IFS is the space, tab, and newline characters by default,连续多个空白被看作一个处理命令行

  2. "$*" 使用IFS中的第一个字符做为分隔符,把参数链接orm

  3. awk中的FS(域分隔符)也和IFS有相似的用法和做用blog


2、IFS 简单实例token

一、查看IFS的值

[root@localhost ~]# set | grep IFS
IFS=$' \t\n'
[root@localhost ~]# echo -n "$IFS" | od -ab
0000000  sp  ht  nl
        040 011 012
0000003

二、"$@" 和 "$*" 异同

*      Expands to the positional parameters, starting from one.  When the expansion occurs within  double quotes,  it expands to a single word with the value of each parameter separated by the first character of the IFS special variable.  That is, "$*" is equivalent to "$1c$2c...",  where  c  is  the first  character  of the value of the IFS variable.  If IFS is unset, the parameters are separated by spaces.  If IFS is null, the parameters are joined without intervening separators.

@      Expands to the positional parameters, starting from one.  When the expansion occurs within  double quotes,  each  parameter expands to a separate word.  That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the  expansion  of  the  first  parameter  is joined  with  the  beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word.  When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

"$@"  "$*"     只有当用双引号quoting时, 它们才有所不一样。

$@     $*       两种结果是相同的。
相关文章
相关标签/搜索