1、IFS是什么?
Linux下有一个特殊的环境变量叫做IFS,叫做内部字段分隔符(internal field separator)。IFS环境变量定义了bash shell用户字段分隔符的一系列字符。默认情况下,bash shell会将空格当做字段分隔符。我这里的系统是Centos7系统。
但是往往我们不能仅仅以空格符来作为字段分隔符,有时候我们需要以换行符设置为分隔符。
演示如下:
现在我创建了四个目录,其中一个目录带有空格。现在我想把一下子他们统统都删除掉。
[root@ELK-chaofeng test]# ls
chao chao feng chen feng
[[email protected]-chaofeng test]# ll
total16drwxr-xr-x 2 root root 4096 Feb 14 11:57chao
drwxr-xr-x 2 root root 4096 Feb 14 10:52chao feng
drwxr-xr-x 2 root root 4096 Feb 14 11:57chen
drwxr-xr-x 2 root root 4096 Feb 14 11:57 feng
如何直接删除的话,会出现下面的情况:
[[email protected] test]# find . -type d
.
./chao feng
./chen
./feng
./for dir in `find . -type d`; doecho ${dir} ;done
.
./chao
feng
./chen
./feng
./chao
上面红色背景的本来是一个目录,结果这里却显示成了两个目录,所以使用rm删除的话肯定是删除不掉的。(我这里使用echo来做演示而已,echo显示正确,那么rm也能顺利删除带有空格的目录)
此时我们就需要使用IFS来解决这个问题了。
[[email protected] test]# IFS=$‘\n‘ && for dir in `find . -type d`; doecho ${dir} ;done
.
./chao feng
./chen
./feng
./chao
这个时候我们发现带有空格的目录可以完整显示了。这是正确的。那么现在我们就可以删除了。
[root@ELK-chaofeng test]# ll
total20drwxr-xr-x 2 root root 4096 Feb 14 11:57chao
drwxr-xr-x 2 root root 4096 Feb 14 10:52chao feng
drwxr-xr-x 2 root root 4096 Feb 14 11:57chen
drwxr-xr-x 2 root root 4096 Feb 14 11:57IFS=$‘\n‘ && for dir in `find . -type d`; do rm -rf ${dir} ;done
rm: refusing to remove ‘.’ or ‘..’ directory: skipping ‘.’
[[email protected]-chaofeng test]# ls
此时rm报错可以忽略。现在看来我们已经成功的结果了这个问题。
原文:https://www.cnblogs.com/FengGeBlog/p/10373901.html