shell脚本判断文件和目录是否存在

来源:互联网 发布:编程 知乎 编辑:程序博客网 时间:2024/05/20 18:19


01#!/bin/sh
02myPath="/var/log/httpd/"
03myFile="/var /log/httpd/access.log"
04# 这里的-x 参数判断$myPath是否存在并且是否具有可执行权限
05if [ ! -x "$myPath"]; then
06mkdir "$myPath"
07fi
08 # 这里的-d 参数判断$myPath是否存在
09 if [ ! -d "$myPath"]; then
10 mkdir "$myPath"
11 fi
12 
13 # 这里的-f参数判断$myFile是否存在
14 if [ ! -f "$myFile" ]; then
15 touch "$myFile"
16 fi
17 # 其他参数还有-n,-n是判断一个变量是否是否有值
18 if [ ! -n "$myVar" ]; then
19 echo "$myVar is empty"
20 exit 0
21 fi
22 
23 # 两个变量判断是否相等
24 if "$var1" "$var2" ]; then
25 echo '$var1 eq $var2'
26 else
27 echo '$var1 not eq $var2'
28 fi
29-f 和-e的区别
30 
31Conditional Logic on Files
32 
33 
34 
35-a file exists.
36 
37-b file exists and is a block special file.
38 
39-c file exists and is a character special file.
40 
41-d file exists and is a directory.
42 
43-e file exists (just the same as -a).
44 
45-f file exists and is a regular file.
46 
47-g file exists and has its setgid(2) bit set.
48 
49-G file exists and has the same group ID as this process.
50 
51-k file exists and has its sticky bit set.
52 
53-L file exists and is a symbolic link.
54 
55-n string length is not zero.
56 
57-o Named option is set on.
58 
59-O file exists and is owned by the user ID of this process.
60 
61-p file exists and is a first in, first out (FIFO) special file or
62 
63named pipe.
64 
65-r file exists and is readable by the current process.
66 
67-s file exists and has a size greater than zero.
68 
69-S file exists and is a socket.
70 
71-t file descriptor number fildes is open and associated with a
72 
73terminal device.
74 
75-u file exists and has its setuid(2) bit set.
76 
77-w file exists and is writable by the current process.
78 
79-x file exists and is executable by the current process.
80 
81-z string length is zero.
82 
83 
84 
85是用 -s 还是用 -f 这个区别是很大的!

原创粉丝点击