Linux之特殊的环境变量IFS以及如何删除带有空格的目录

1、IFS是什么?

Linux下有一个特殊的环境变量叫做IFS,叫做内部字段分隔符(internal field separator)。IFS环境变量定义了bash shell用户字段分隔符的一系列字符。默认情况下,bash shell会将空格当做字段分隔符。我这里的系统是Centos7系统。

但是往往我们不能仅仅以空格符来作为字段分隔符,有些情况下我们需要将分割符设置为换行符来满足我们的业务需求。

演示如下:

现在我创建了四个目录,其中一个目录带有空格。现在我想把一下子他们统统都删除掉。

[root@ELK-chaofeng test]# ls
chao  chao feng  chen  feng
[root@ELK-chaofeng test]# ll
total 16
drwxr-xr-x 2 root root 4096 Feb 14 11:57 chao
drwxr-xr-x 2 root root 4096 Feb 14 10:52 chao feng
drwxr-xr-x 2 root root 4096 Feb 14 11:57 chen
drwxr-xr-x 2 root root 4096 Feb 14 11:57 feng

如何直接删除的话,会出现下面的情况:

[root@ELK-chaofeng test]# find . -type d
.
./chao feng
./chen
./feng
./chao
[root@ELK-chaofeng test]# for dir in `find . -type d`; do echo ${dir} ;done
.
./chao
feng
./chen
./feng
./chao

上面红色背景的本来是一个目录,结果这里却显示成了两个目录,所以使用rm删除的话肯定是删除不掉的。(我这里使用echo来做演示而已,echo显示正确,那么rm也能顺利删除带有空格的目录)

此时我们就需要使用IFS来解决这个问题了。

[root@ELK-chaofeng test]# IFS=$'
' && for dir in `find . -type d`; do echo ${dir} ;done
.
./chao feng
./chen
./feng
./chao

这个时候我们发现带有空格的目录可以完整显示了。这是正确的。那么现在我们就可以删除了。

[root@ELK-chaofeng test]# ll
total 20
drwxr-xr-x 2 root root 4096 Feb 14 11:57 chao
drwxr-xr-x 2 root root 4096 Feb 14 10:52 chao feng
drwxr-xr-x 2 root root 4096 Feb 14 11:57 chen
drwxr-xr-x 2 root root 4096 Feb 14 11:57 feng
[root@ELK-chaofeng test]# IFS=$'
' && for dir in `find . -type d`; do rm -rf ${dir} ;done
rm: refusing to remove ‘.’ or ‘..’ directory: skipping ‘.’
[root@ELK-chaofeng test]# ls

此时rm报错可以忽略。现在看来我们已经成功的结果了这个问题。

原文地址:https://www.cnblogs.com/FengGeBlog/p/10373901.html