最も長いファイル名を持つファイルを見つけるスクリプトを作成するのに役立ちます。

最も長いファイル名を持つファイルを見つけるスクリプトを作成するのに役立ちます。

そのディレクトリで最も多くの文字を含むファイルを見つけるために、ファイルディレクトリ全体を繰り返すスクリプトを作成しようとしています。添付のコードサンプルは次のとおりです。私は何が間違っていましたか?

  1 #!/bin/bash
  2 #This program takes an array of files and sees which is the largest in a directory
  3 
  4 files=() #create an Empty array for which files will be stored
  5 longest=${files[0]} #Sets point of origin for the current largest file at 0
  6 
  7 echo "Enter Directory name:"
  8 read dir_name
  9 
 10 if [ -d "$dir_name" ]; then #Test file to see if it's a directory
 11 
 12         for i in "$dir_name"/* #For loop to discern the file with the most characters
 13            do
 14                 files=$dir_name
 15                 if [ "${#i}" -gt "${#longest}" ]; then
 16                         longest="$i"
 17                         echo "$i && Character count:${#files[i]}"
 18                 fi
 19            done
 20 
 21 elif [ ! -d "$dir_name" ]
 22 then
 23         echo "Sorry not the directory we are looking for"
 24         exit 0
 25 fi
 26 
 27 

ベストアンサー1

あなたのコードにいくつかのエラーがあります。

  1. ループにはfor開始または終了にaがありません。dodone
  2. if [ ... ] then一行で書いたら、;に入れなければなりませんthen
  3. スクリプトの目的でファイルを配列に保存する必要はなく、ディレクトリ内のファイルを直接繰り返すことができます。

更新:目的のタスクを実行するためにスクリプトを書き直しました。ディレクトリから最も長いファイル名を持つファイルを取得し、文字数を使用して印刷します。

#!/bin/bash

longest=0

if [ $# -lt 1 ]; then # if no argument given, read the directory from input
    echo -n "Enter directory name: "
    read dir_name
else
    dir_name=$1 # this allows execute the script with the directory as argument
fi

if [ -d "$dir_name" ]; then # process if what was given is a directory
    for file in "$dir_name"/* ; do
        if [ -f "$file" ]; then # do it only for files
            filename=$(basename $file) # get only the filename: NOT in all UNIX
            if [ ${#filename} -gt $longest ]; then
                longest=${#filename} # store new longest
                longest_file=$file # save the file
            fi
        fi
    done
    # we are done, print results
    echo -n "The file with longest filename is" $longest_file
    echo " with a filename" $longest "characters long"
fi

テスト:

次の一般ファイルを含む「test」ディレクトリが提供されます。

a ab abc abcd

スクリプトの出力は次のとおりです。

The file with longest filename is test/abcd with a filename 4 characters long

おすすめ記事