File test operations-advanced bash Script Programming Guide

Source: Internet
Author: User

File test operations-advanced bash Script Programming Guide

/Span> 7.2 file testing operations
----------------
Returns true if...
-E file exists
-File a exists.
This option has the same effect as-e, but it has been discarded and is not encouraged.
-F file is a regular file (not a directory or a device file)
-S file length is not 0
-D files are directories.
-File B is a block device (floppy disk, cdrom, etc)
-The c file is a character device (keyboard, modem, sound card, etc)
-The p file is a pipeline.
-H file is a symbolic link
-L the file is a symbolic link
-S file is a socket
-T file descriptor associated with a terminal device
This option is generally used to check whether stdin [-t0] or [-t1] in a given script is a terminal.
-R file has read permission (for the user to run this test)
-W file has write permission (for the user to run this test)
-The x file has the execution permission (for the user to run this test)

-Size: 11pt; color: rgb (, 0); font-style-g set-group-id (sgid) flag to the file or directory
If a directory has the sgid flag, a file is created in this directory, which belongs to the Created directory.
The User Group of this directory is not necessarily the same as the group of users who created this file. For the workgroup directory
This is useful for sharing. For more information, see <UNIX environment advanced programming Chinese version> page 58th.
-U set-user-id (suid) flag to the file
If you run a file with the root permission, the running process will get the root permission, even if you are a normal
User. [1] This is useful for operations that require access to system hardware (such as pppd and cdrecord). If
Without the suid flag, normal users (without the root permission) will not be able to run this program.
See <English version of advanced programming in UNIX environment> page 58th.
-Rwsr-xr-t 1 root 178236 Oct 2 2000/usr/sbin/pppd
For files with suid set, the permission flag contains "s ".
-K. For more information about how to set the pasting position, see <UNIX advanced programming Chinese version> page 65th.
For "sticky bit", the save-text-mode flag is a special type of File Permission. If this
The file will be saved in the SWAp zone for quick access.
. For files or directories with sticky bit configured, the permission flag contains "t ".
Drwxrwxrwt 7 root 1024 May 19 tmp/
If a user who has stick bit directory owner but has write permission from time to time
You can delete your own files in this directory. This will prevent users from accidentally overwriting the files in a public directory.
Or delete other files, such as/tmp (of course, the root or directory owner can delete or rename the files.
Files ).

-Webkit-text-stroke-width: 0px; "> f1-nt f2
File f1 is newer than f2
F1-ot f2
F1 is older than f2
F1-ef f2
Both f1 and f2 are hard connected to the same file.
! Non--- reverse the result of the above test (true will be returned if the condition is absent)

Binary comparison operator, which compares variables or numbers. Note the difference between numbers and strings.
Integer comparison
-Eq equals to, for example, if ["$ a"-eq "$ B"]
-Ne is not equal to, for example, if ["$ a"-ne "$ B"]
-Gt is greater than, for example, if ["$ a"-gt "$ B"]
-Ge is greater than or equal to, for example, if ["$ a"-ge "$ B"]
-Lt is less than, for example, if ["$ a"-lt "$ B"]
-Le is less than or equal to, for example, if ["$ a"-le "$ B"]
<Less than (double parentheses are required), such as: ("$ a" <"$ B "))
<= Less than or equal to (double parentheses are required), for example: ("$ a" <= "$ B "))
> Greater than (double parentheses are required), such as: ("$ a"> "$ B "))
> = Equal to or greater than (double parentheses required), for example: ("$ a"> = "$ B "))
String comparison
= Equals, for example, if ["$ a" = "$ B"]
= Equal to, such as: if ["$ a" = "$ B"], equivalent to =
Note: The = function has different behaviors in [[] and [], as shown below:
1 [[$ a = z *] # true if $ a starts with "z" (pattern matching)
2 [[$ a = "z *"] # If $ a is equal to z * (character matching), the result is true.
3
4 [$ a = z *] # File globbing and word splitting will occur
5 ["$ a" = "z *"] # If $ a is equal to z * (character matching), the result is true.
For a bit of explanation, File globbing is a stenographer of files, for example, "*. c" is, and then ~ Yes.
But file globbing is not a strict regular expression, although the structure is similar in most cases.
! = Not equal to, such as: if ["$ "! = "$ B"]

Version: 0.9 StartHTML: 00000097 EndHTML: 00031529 StartFragment: 00000135 EndFragment: 00031491 this operator uses pattern matching in the [[] structure.
<Less than, in the ASCII alphabetic order. For example:
If [["$ a" <"$ B"]
If ["$ a" \ <"$ B"]
Note: "<" must be escaped in the [] structure.
> Greater than, in the ASCII alphabetic order. For example:
If [["$ a"> "$ B"]
If ["$ a" \> "$ B"]
Note: ">" needs to be escaped in the [] structure.
For more information, see Example 26-11.
-Z string is "null". The length is 0.
-N string is not "null"
Note:
To use-n in the [] structure, you must use "" To cause variables. Use a string that is not! -Z
Or the strings that are not referenced by "" are put in the [] structure (see Example 7-6 ).
It is a good habit to use "" To test strings. [1]
Example 7-5 Comparison of numbers and strings
################################ Start
Script #######################################
1 #! /Bin/bash
2
3 a = 4
4 B = 5
5
6 # The variables a and B can be both integer and string.
7 # Here there is some confusion between arithmetic comparison and string comparison,
8 # + Bash variables are not strongly typed.
9
10 # Bash allows operations and comparison of Integer Variables
11 # + of course, the variable only contains numeric characters.
12 # But you still need to make it clear.
13
14 echo
15
16 if ["$ a"-ne "$ B"]
17 then
18 echo "$ a is not equal to $ B"
19 echo "(arithmetic comparison )"
20 fi
21
22 echo
23
24 if ["$ "! = "$ B"]
25 then
26 echo "$ a is not equal to $ B ."
27 echo "(string comparison )"
28 #"4 "! = "5"
29 # ASCII 52! = ASCII 53
30 fi
31
32 # in this particular example, "-ne" and "! = "Yes.
33
34 echo
35
36 exit 0
################################ End
Script ####################################### ##
Example 7-6 test whether the string is null
################################ Start
Script #######################################
1 #! /Bin/bash
2 # str-test.sh: test the null String and non-referenced string,
3 # + but not strings and sealing wax, not to mention cabbages and kings...
4 # + the above sentence is not understood
5 # Using if [...]
6
7
8 # If a string is not initialized, it has no defined value (like this, it always feels like a fart)
9 # this state is called "null" (different from zero)
10
11 if [-n $ string1] # $ string1 is not declared and initialized
12 then
13 echo "String \" string1 \ "is not null ."
14 else
15 echo "String \" string1 \ "is null ."
16 fi
17 # incorrect results.
18 # Show $ string1 is not empty, although it is not initialized.
19
20
21 echo
22
23
24 # Let's try again.
25
26 if [-n "$ string1"] # $ string1 is referenced this time.
27 then
28 echo "String \" string1 \ "is not null ."
29 else
30 echo "String \" string1 \ "is null ."
The 31 fi # "" string is in the [] Structure
32
33
34 echo
35
36
37 if [$ string1] # This time $ string1 becomes "naked"
38 then
39 echo "String \" string1 \ "is not null ."
40 else
41 echo "String \" string1 \ "is null ."
42 fi
43 # This works well.
44 # This [] test operation checks whether the string is null.
45 # However, using ("$ string1") is a good habit
46 #
47 # As steane Chazelas points out,
48 # if [$ string1] has 1 parameter "]"
49 # if ["$ string1"] has two parameters, null "$ string1" and "]"
50
51
52
53 echo
54
55
56
57 string1 = initialized
58
59 if [$ string1] # Come back, $ string1 "naked"
60 then
61 echo "String \" string1 \ "is not null ."
62 else
63 echo "String \" string1 \ "is null ."
64 fi
65 # Then, the correct results are given.
66 # But how to say ("$ string1") is much better, because...
67
68
69 string1 = "a = B"
70
71 if [$ string1] # Then, $ string1 is naked again.
72 then
73 echo "String \" string1 \ "is not null ."
74 else
75 echo "String \" string1 \ "is null ."
76 fi
77 # The unreferenced "$ string1" is now giving an error!
78
79 exit 0
80 # Thank you, also, Florian Wisser, for the "heads-up ".
################################ End
Script ####################################### ##
Example 7-7 zmore
################################ Start
Script #######################################
1 #! /Bin/bash
2 # zmore
3
4 # Use 'more' to view gzip files
5
6 NOARGS = 65
7 NOTFOUND = 66
8 NOTGZIP = 67
9
10 if [$ #-eq 0] # Same effect as if [-z "$1 "]
11 # It should be that there is a problem with the comments in the front, $1 can exist, for example: zmore "" arg2 arg3
12 then
13 echo "Usage: 'basename $ 0' filename"> & 2
14 # error message to stderr
15 exit $ NOARGS
16 # The script returns 65 as the exit code.
17 fi
18
19 filename = $1
20
21 if [! -F "$ filename"] # add $ filename "to allow possible blank spaces
22 then
23 echo "File $ filename not found! "> & 2
24 # error message to stderr
25 exit $ NOTFOUND
26 fi
27
28 if [$ {filename ##*.}! = "Gz"]
29 # Use brackets in variable replacement
30 then
31 echo "File $1 is not a gzipped file! "
32 exit $ NOTGZIP
33 fi
34
35 zcat $1 | more
36
37 # Use the filter command 'more'
38 # If you want to do so, you can also use 'less'
39
40
41 exit $? # The script returns the pipe result as the exit code.
42 # In fact, "exit $? ", But in any case, with this sentence, it can be formal.
43 # Return the execution status of the last command as the exit code
################################ End
Script ####################################### ##
Hybrid comparison
-A logic and
Exp1-a exp2 if both exp1 and exp2 are true, this expression returns true
-O logic or
Exp1-o exp2 if either exp1 or exp2 is true, the expression returns true.
This is very similar to the Bash comparison operator & |. Use it in.
1 [[condition1 & condition2]
-O and-a generally work with the test command or.
1 if ["$ exp1"-a "$ exp2"]
See Example 8-3, Example 26-16 and Example A-28 to view the behavior of a hybrid comparison operation. note: [1] S. c. (This guy is a personal name) points out that even "$ var" may cause problems when using hybrid comparison. if $ string is empty, [-n "$ string"-o "$ a" = "$ B"] may be faulty in some versions of Bash. to append an extra character to a possible null variable, a safe way is to ["x $ string "! = X-o "x $ a" = "x $ B"] (the "x's" cancel out) (not understood ). cancel out is offset. 7.4 nested if/then condition test ------------------------- you can use if/then for nested condition test. the final result is the same as the use & hybrid comparison operation above. 1 if [condition1] 2 then3 if [condition2] 4 then5 do-something # Here only when both condition1 and condition2 are available. 6 fi7 fi For details, refer to Example 34-4.7.5 check your test knowledge ------------------ the xinitrc file within the system can be used to start X server. this file contains quite a few if/then test files, just like the excerpt below: 1 if [-f $ HOME /. xclients]; then2 exec $ HOME /. xclients3 elif [-f/etc/X11/xinit/Xclients]; then4 exec/etc/X11/xinit/Xclients5 else6 # fault Insurance settings, although we will never come here. 7 # (we also provide the same mechanism in Xclients) It will not hurt. 8 xclock-geometry 100x100-5 + 5 & 9 xterm-geometry 80x50-50 + 150 & 10 if [-f/usr/bin/netscape-a-f/usr/share/doc/HTML/ index.html]; then11 netscape/usr/share/doc/HTML/index.html & 12 fi13 fi explained the above "test" structure, then checked the entire file,/etc/X11/xinit/xinitrc, analyze the if/thentest structure. you may need to check the knowledge about grep, sed, and regular expressions that can be explained later.

7.4 nested if/then condition test
-------------------------
You can use if/then for nested condition test. The final result is the same as the use & hybrid comparison operation above.

Ight: normal; letter-spacing: normal; 1 if [condition1]
2 then
3 if [condition2]
4 then
5 do-something # only when both condition1 and condition2 are available.
6 fi
7 fi
For details, see Example 34-4.
7.5 check your test knowledge
--------------------
The xinitrc file in the system can be used to start X server. This file contains a large number of if/then test files,
Just like the excerpt below:
1 if [-f $ HOME/. Xclients]; then
2 exec $ HOME/. Xclients
3 elif [-f/etc/X11/xinit/Xclients]; then
4 exec/etc/X11/xinit/Xclients
5 else
6 # fault Insurance settings, although we will never come here.
7 # (we also provide the same mechanism in Xclients) It will not hurt.
8 xclock-geometry 100x100-5 + 5 &
9 xterm-geometry 80 x50-50 + 150 &
10 if [-f/usr/bin/netscape-a-f/usr/share/doc/HTML/index.html]; then
11 netscape/usr/share/doc/HTML/index.html &
12 fi
13 fi
Explain the above "test" structure, check the entire file,/etc/X11/xinit/xinitrc, and analyze if/then
Test structure. You may need to check the grep, sed, and regular expression knowledge that can be explained later.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.