xunwap

专注移动互联网服务

正在浏览 Linux 里的文章

下面的shell用于在linux下测试文件的相关特性。记录如下,以备查阅.

用法                                                                     功能
-b file                         True if file exists and is a block special file.
-c file                         True if file exists and is a character special file.
-d file                         True if file exists and is a directory.
-e file                         True if file exists.
-f file                          True if file exists and is a regular file.
-g file                         True if file exists and has its SGID bit set.
-h file                       True if file exists and is a symbolic link.
-k file                        True if file exists and has its “sticky” bit set.
-p file                        True if file exists and is a named pipe.
-r file                        True if file exists and is readable.
-s file                        True if file exists and has a size greater than zero.
-u file                       True if file exists and has its SUID bit set.
-w file                       True if file exists and is writable.
-x file                       True if file exists and is executable.
-O file                       True if file exists and is owned by the effective user ID.

本站原创文章,转载请注明出处。

在Linux下,有时我们需要按顺序连接执行几个命令,如Cmd_1 -> Cmd_2。同时我们需要保证如果前一个命令执行失败,那么后一个命令将不能执行。于是,可能会出现如下的脚本:

#!/bin/sh
Cmd_1
Cmd_2

表面上看这样似乎没有问题,但是在某些特殊的情况下,这样的操作是十分危险的,比如,我们当前位于 /data 目录中,现在我们需要进行 /data/foo 目录,然后删除 foo 目录下的所有的子目录和文件,一点典型的做法是:

#!/bin/sh
cd ./foo
rm -rf ./*

看起来不错,也能完成任务,但是试想,如果某次执行这个命令时,foo 目录不存在,那么”cd ./foo” 就会失败,所以依旧位于”/data”目录,但是,接下来的”rm -rf ./*” 还是会执行,也就相当于执行了 “rm -rf /data/*”。现在你应该意识到问题了,执行这个命令之后,你的 “/data” 目录下的所有的数据都被删除了。

当然,有的人说,可以先判断”cd ./foo” 的执行结果,然后判断是否执行”rm -rf ./*”。这样是可以的,不过还有一种更好的办法,那么就是使用shell中的”&&”运算符了。

“&&” 运算符用于连接两个命令,使用方式为 “Cmd_1 && Cmd_2″。并且”&&”运算符保证,只有在Cmd_1执行成功之后,才会去执行”Cmd_2″。这个特性也就可以很好地解决我们遇到的问题了。脚本如下:

#!/bin/sh

cd ./foo && rm -rf ./*

灵活地运用shell自身的特性,不但能简化操作而且能保证命令执行的安全性。

本站原创文章,转载请注明出处。