Bash Commands - File test operators

来源:互联网 发布:唯美的句子 知乎 编辑:程序博客网 时间:2024/06/05 10:46
Returns true if...


-e             file exists

-a             file exists.     This is identical in effect to -e. It has been "deprecated," [34] and its use is discouraged.

-f              file is a regular file (not a directory or device file)
-s            file is not zero size
-d             file is a directory
-b             file is a block device
-c              file is a character device


device0="/dev/sda2"

# /
(root directory)
if [ -b "$device0" ]
then
echo "$device0 is a block device."
fi


# /dev/sda2 is a block device.

device1="/dev/ttyS1"
# PCMCIA modem card.
if [ -c "$device1" ]
then
echo "$device1 is a character device."
fi

# /dev/ttyS1 is a character device.


-p                      file is a pipe


function show_input_type()

{
[ -p /dev/fd/0 ] && echo PIPE || echo STDIN
}
show_input_type "Input"                             
# STDIN

echo "Input" | show_input_type                  # PIPE



-h                      file is a symbolic link

-L                         file is a symbolic link

-S                         file is a socket
-t                           file (descriptor) is associated with a terminal device
This test option may be used to check whether the stdin [ -t 0 ] or stdout [ -t 1 ] in a
given script is a terminal.
-r                           file has read permission (for the user running the test)
-w                       file has write permission (for the user running the test)
-x                         file has execute permission (for the user running the test)
-g                         set-group-id (sgid) flag set on file or directory

If a directory has the sgid flag set, then a file created within that directory belongs to the group that
owns the directory, not necessarily to the group of the user who created the file. This may be useful
for a directory shared by a workgroup.

-u                            set-user-id (suid) flag set on file

-k                            sticky bit set

-O                             you are owner of file
-G                             group-id of file same as yours
-N                             file modified since it was last read
f1 -nt f2                    file f1 is newer than f2
f1 -ot f2                    file f1 is older than f2
f1 -ef f2                    files f1 and f2 are hard links to the same file
!                                    "not" -- reverses the sense of the tests above (returns true if condition absent).