Bash Shell获取文件的相关信息,你需要文件的更多相关信息,例如类型、属主、是否可执行、有多少硬链接,以及最后一次访问或更改的时间。
解决方案
使用 ls、stat、file 或 find 命令:
$ touch /coolcou/sample_file
$ ls /coolcou/sample_file
/coolcou/sample_file
$ ls -l /coolcou/sample_file
-rw-r--r-- 1 jp jp 0 Dec 18 15:03 /coolcou/sample_file
$ stat /coolcou/sample_file
File: "/coolcou/sample_file"
Size: 0 Blocks: 0 IO Block: 4096 Regular File
Device: 303h/771d Inode: 2310201 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 501/ jp) Gid: ( 501/ jp)
Access: Sun Dec 18 15:03:35 2005
Modify: Sun Dec 18 15:03:35 2005
Change: Sun Dec 18 15:03:42 2005
$ file /coolcou/sample_file
/coolcou/sample_file: empty
$ file -b /coolcou/sample_file
empty
$ echo '#!/bin/bash -' > /coolcou/sample_file
$ file /coolcou/sample_file
/coolcou/sample_file: Bourne-Again shell script text executable
$ file -b /coolcou/sample_file
Bourne-Again shell script text executable
讨论
ls 命令只显示文件名,-l 选项可以提供每个文件更详细的信息。ls 的选项很多,可以查询手册页了解其所支持的选项,其中有用的选项包括以下几个。
- -a
不隐藏以 .(点号)开头的文件。 - -A
和 -a 相似,但不显示两个常见的目录 . 和 ..,因为每个目录中都有这两项。 - -F
文件名结尾以下列类型标识符之一显示文件类型。
斜线(/)表示该文件是目录,星号(*)表示该文件是可执行文件,@ 表示符号链接,等号(=)表示套接字,竖线(|)表示 FIFO(first in, first out)缓冲。 - -l
使用长列表格式。 - -L
显示链接目标文件的信息,而非符号链接本身。 - -Q
引用名(quote name)(GNU 扩展,仅部分系统支持)。 - -r
逆序排列。 - -R
递归显示子目录。 - -S
按照文件大小排序。 - -1
使用短格式,每行只显示一个文件。
stat、file 和 find 命令都拥有众多控制输出格式的选项,你可以查询手册页了解它们所支持的选项。例如,下列这些选项可以生成类似于 ls -l 的输出:
$ ls -l /coolcou/sample_file
-rw-r--r-- 1 jp jp 14 Dec 18 15:04 /coolcou/sample_file
$ stat -c'%A %h %U %G %s %y %n' /coolcou/sample_file
-rw-r--r-- 1 jp jp 14 Sun Dec 18 15:04:12 2005 /coolcou/sample_file
$ find /coolcou/ -name sample_file -printf '%m %n %u %g %t %p'
644 1 jp jp Sun Dec 18 15:04:12 2005 /coolcou/sample_file
注意,并非所有操作系统及其各版本都有这些工具。例如,Solaris 就默认不包含 stat。
另外值得指出的是,目录其实就是一种操作系统会特别处理的文件,因此本文展示的这些命令也完全能够应用于目录,只不过有时可能需要修改命令才能得到想要的结果。例如,可以用 ls -d 列出目录本身的信息(不加该选项的 ls 列出的是目录的内容)。
酷客网相关文章:
评论前必须登录!
注册