文字特殊ファイルとブロック特殊ファイルの存在をテストするためのシェルスクリプト

文字特殊ファイルとブロック特殊ファイルの存在をテストするためのシェルスクリプト

私の作業ディレクトリには2つのファイルがあります。

test.txtそしてimg.jpg

test.txtキャラクター特殊ファイルです

img.jpgブロックは特殊ファイルです

シェルスクリプトを使用して、これらのファイルが文字特殊ファイルかブロック特殊ファイルかを確認したいと思います。

私は次の2つのシェルスクリプトを書きました。

最初 -

#! /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

入力する:

test.txt

出力:

Character special file test.txt not found

第二 -

#! /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

入力する:

img.jpg

出力:

Block special file img.jpg not found

私はどこで間違っていますか?

ベストアンサー1

あなたの家はやや間違っています。ブロック特殊ファイルは、ハードディスクパーティション、メモリデバイスなどを意味します。たとえば、私のハードドライブのデフォルトのパーティションはです/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

ttyやシリアルコンソールなどの文字デバイス。たとえば、

$ test -c /dev/tty1 && echo "It's a character device" || echo "Not a character dev"                                          
It's a character device

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

あなたがする必要があるのは、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

おすすめ記事