如果不使用文件命令,您将如何完成它。我正在尝试打印当前目录中的所有文件及其类型。
./type.bash *
Desktop (Directory)
Documents (Directory)
Downloads (Directory)
Music (Directory)
list (Ordinary file)
答案1
您可以使用统计数据。
$ touch regular_file
$ mkdir directory
$ stat -c %F regular_file directory/
regular empty file
directory
$
$ stat --format="%n: %F" regular_file directory
regular_file: regular empty file
directory: directory
答案2
如果您只想区分文件和目录,但对文件类型不感兴趣,那么这是一个简约的示例。
find . -mindepth 1 -type d -printf '%f (Directory)\n' && find . -type f -printf '%f (Ordinary file)\n'
使用该find
命令,首先列出目录,然后列出第二个命令中的文件。第一个命令中的目的-mindepth 1
是跳过.
指示当前目录。
由于找到的是递归的您可能想要添加该-maxdepth 1
选项。
答案3
如果您的老师希望您复制问题中显示的输出,他们可能希望您执行以下操作:
#!/bin/sh
for f
do
if [ -d "$f" ]
then
printf '%s (%s)\n' "$f" Directory
elif [ -f "$f" ]
then
printf '%s (%s)\n' "$f" 'Ordinary file'
else
printf '%s (%s)\n' "$f" Other
fi
done
这是纯粹的 bash。
如果您更喜欢使用外部程序,您可以这样做:
#!/bin/sh
for f
do
case "$(ls -ld "$f")" in
d*)
printf '%s (%s)\n' "$f" Directory
;;
-*)
printf '%s (%s)\n' "$f" 'Ordinary file'
;;
*)
printf '%s (%s)\n' "$f" Other
esac
done
答案4
带着这样的问题,您应该做的第一件事就是阅读file
联机帮助页(man 1 file
)。正如其文档中所述:
The filesystem tests are based on examining the return from a stat(2) system
call. The program checks to see if the file is empty, or if it's some sort of
special file. Any known file types appropriate to the system you are running
on (sockets, symbolic links, or named pipes (FIFOs) on those systems that
implement them) are intuited if they are defined in the system header file
<sys/stat.h>.
The magic tests are used to check for files with data in particular fixed for‐
mats. The canonical example of this is a binary executable (compiled program)
a.out file, whose format is defined in <elf.h>, <a.out.h> and possibly
<exec.h> in the standard include directory. These files have a “magic number”
stored in a particular place near the beginning of the file that tells the
UNIX operating system that the file is a binary executable, and which of sev‐
eral types thereof. The concept of a “magic” has been applied by extension to
data files. Any file with some invariant identifier at a small fixed offset
into the file can usually be described in this way. The information identify‐
ing these files is read from /etc/magic and the compiled magic file
/usr/share/misc/magic.mgc, or the files in the directory /usr/share/misc/magic
if the compiled file does not exist. In addition, if $HOME/.magic.mgc or
$HOME/.magic exists, it will be used in preference to the system magic files.
file
依赖于幻数。因此,如果您想自己实现一个等效的文件,您必须首先stat
检查它是否是常规文件,如果它不为空,然后使用幻数。考虑使用libmagic
它可以为您做到这一点。