用于测试字符特殊文件和块特殊文件是否存在的 Shell 脚本

Son*_*vol 2 filesystems shell-script

我的工作目录中有以下两个文件:

test.txtimg.jpg

test.txt是一个字符特殊文件

img.jpg是一个块特殊文件

现在我想使用 shell 脚本查找这些文件是字符特殊文件还是块特殊文件。

我写了以下两个shell脚本:

第一的-

#! /bin/bash

echo -e "Enter file name: \c"
read file_name

if [ -c $file_name ]
then
    echo Character special file $file_name found
else
    echo Character special file $file_name not found
Run Code Online (Sandbox Code Playgroud)

输入:

test.txt
Run Code Online (Sandbox Code Playgroud)

输出:

Character special file test.txt not found
Run Code Online (Sandbox Code Playgroud)

第二-

#! /bin/bash

echo -e "Enter file name: \c"
read file_name

if [ -b $file_name ]
then
    echo Block special file $file_name found
else
    echo Block special file $file_name not found
Run Code Online (Sandbox Code Playgroud)

输入:

img.jpg
Run Code Online (Sandbox Code Playgroud)

输出:

Block special file img.jpg not found
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

Ser*_*nyy 5

你的假设有点错误。块特殊文件是指硬盘分区、内存设备等。例如,我的硬盘驱动器的主分区是/dev/sda1. 测试的(又名[-b标志将适用于此,但它不适用于图片文件,该文件被视为常规文件。

$ test -b ./Pictures/NOTEBOOKS/8.jpg && echo "It's a block device" || echo "Not  a block device"                                                                                        
Not  a block device
$ test -b /dev/sda1  && echo "It's a block device" || echo "Not  a block device"                                                                                                        
It's a block device
Run Code Online (Sandbox Code Playgroud)

字符设备例如 tty 和串行控制台。例如:

$ test -c /dev/tty1 && echo "It's a character device" || echo "Not a character dev"                                          
It's a character device
Run Code Online (Sandbox Code Playgroud)

并且stat可以告诉您几乎相同的信息,只是以文本形式而不是像这样的退出状态test

$ stat --printf "%n\t%F\n"  /dev/tty1 /dev/sda1 ./mytext.txt ./Pictures/NOTEBOOKS/8.jpg                                      
/dev/tty1   character special file
/dev/sda1   block special file
./mytext.txt    regular file
./Pictures/NOTEBOOKS/8.jpg  regular file
Run Code Online (Sandbox Code Playgroud)

您应该做的是使用file命令并检查其输出:

$ file ./Pictures/NOTEBOOKS/8.jpg                                                                                                                                                       
./Pictures/NOTEBOOKS/8.jpg: JPEG image data, JFIF standard 1.02, aspect ratio, density 100x100, segment length 16, baseline, precision 8, 750x750, frames 3
$ file /dev/sda1
/dev/sda1: block special (8/1)
$ file mytext.txt
mytext.txt: ASCII text
Run Code Online (Sandbox Code Playgroud)