字段分隔符 IFS - Linux Shell 脚本

内部字段分隔符(Internal Field Separator, IFS)定义一个定界符,默认是空格。

下面是一个示例:

#!/bin/bash

oldIFS=$IFS;
IFS=":";

count=0;
for item in $PATH;
do
    count=$(( count + 1 ))
    printf "%s\t%s\n" $count $item;
done

IFS=$oldIFS;

程序运行结果如下:

wm@WangubuntuConsole:~/shellScriptBlog$ chmod a+x ifs.sh; ./ifs.sh
1       /home/wm/.vscode-server-insiders/bin/84236851a9116f468345f6e8a737015d/bin
2       /home/wm/bin
3       /home/wm/.local/bin
4       /home/wm/.vscode-server-insiders/bin/84236851a9116f468345f6e8a737015d/bin
5       /usr/local/sbin
6       /usr/local/bin
7       /usr/sbin
8       /usr/bin
9       /sbin
10      /bin
11      /usr/games
12      /usr/local/games
13      /snap/bin
wm@WangubuntuConsole:~/shellScriptBlog$ 

IFS被设置为:时,shell将:看作分隔符,因此$item在每次迭代中读取由冒号分隔的子串作为变量值。

你可能感兴趣的:(字段分隔符 IFS - Linux Shell 脚本)